Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果css具有样式,则jquery将类添加到元素_Javascript_Jquery_Css - Fatal编程技术网

Javascript 如果css具有样式,则jquery将类添加到元素

Javascript 如果css具有样式,则jquery将类添加到元素,javascript,jquery,css,Javascript,Jquery,Css,请看下面的问题和答案,第二个答案(有很多赞成票) 看起来像这样: if ($('#yourElement').css('position') == 'absolute') { // true } 这太棒了,但我想要 if ($('#yourElement').css('position') == 'absolute') { $(this).addClass('xxx'); } 因此ID为“yourElement”的元素添加了一个类 将$(“#yourElement”)分配给

请看下面的问题和答案,第二个答案(有很多赞成票)

看起来像这样:

if ($('#yourElement').css('position') == 'absolute') {
    // true
}
这太棒了,但我想要

if ($('#yourElement').css('position') == 'absolute') {
    $(this).addClass('xxx');
}
因此ID为“yourElement”的元素添加了一个类

$(“#yourElement”)
分配给变量最简单的方法是什么。然后对该变量执行检查,并将类添加到该变量中。在您的示例中,这只是节省了使用
$()
函数对DOM进行查询的数量,并且可能需要进一步操作

例如:

var your_element = $('#yourElement');
if (your_element.css('position') == 'absolute') { your_element.addClass('xxx'); }

你可以这样做:

$('#yourElement').addClass(function(index, currentClass) {
    return $(this).css('position') == 'absolute' ? 'xxx' : '';
});

有关语法的更多信息,请查看。

这一条我最喜欢,谢谢你,也谢谢所有其他人
// Cache your element first
var $element = $('#yourElement');

if ($element.css('position') == 'absolute') {
    $element.addClass('xxx');
}
$('#yourElement').addClass(function(index, currentClass) {
    return $(this).css('position') == 'absolute' ? 'xxx' : '';
});