jQuery 如何使用attr获取样式值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16549137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:20:50  来源:igfitidea点击:

How to get the style value using attr

jqueryhtmlcssattr

提问by Dilini Wasana

My HTML CODE HERE:

我的 HTML 代码在这里:

 <i id="bgcolor" style="background-color: rgb(255, 146, 180)"></i>

I want to get the background-color value using jquery attr. What i tried is below:

我想使用 jquery attr 获取背景颜色值。我试过的如下:

$("#bgcolor").mouseleave(function(){
        var bodyColor = $(this).attr("style");

        $("body").css(bodyColor);
    });

But this output is:

但是这个输出是:

background-color: rgb(255, 146, 180);

And now that I've added it to my css it will not work. How can I achieve this task?

现在我已将它添加到我的 css 中,它将无法正常工作。我怎样才能完成这个任务?

enter image description here

在此处输入图片说明

回答by dwaddell

Check out the documentation for .css: http://api.jquery.com/css/

查看 .css 的文档:http: //api.jquery.com/css/

var bodyColor = $(this).css("backgroundColor");

回答by Niccolò Campolungo

This is what you are looking for(this code works):

这就是您要查找的内容(此代码有效):

$("#bgcolor").mouseleave(function(){
    var bodyColor = $(this).attr("style");
    $("body").attr("style", bodyColor);
});

But, instead of using attryou should use css, so the code will be:

但是,attr您应该使用,而不是使用css,因此代码将是:

$("#bgcolor").mouseleave(function(){
    var bodyColor = $(this).css("background-color");
    $("body").css("background-color", bodyColor);
});

JSFiddle

JSFiddle

回答by Cam

I believe this should do the trick, replace your

我相信这应该可以解决问题,替换您的

$("body").css(bodyColor);

With

$("body").attr('style', $(this).attr("style"));

That should change the style to whatever the style on the other object is.

这应该将样式更改为其他对象上的任何样式。

回答by Klors

You can use the $("#bgcolor").css("backgroundColor");to obtain the colour.

您可以使用$("#bgcolor").css("backgroundColor");来获取颜色。

回答by Rajender Joshi

Demo

演示

$("#bgcolor").mouseleave(function(){
    var bodyColor = $(this).css("background-color");
    $("body").css("background-color",bodyColor);
});