简体   繁体   English

通过CSS属性选择jQuery

[英]Select jQuery by CSS attribute

I am trying to select an image by the CSS that is automatically applied through a CMS to that image and then add a class. 我试图通过CSS选择一个图像,该CSS通过CMS自动应用于该图像,然后添加一个类。 Here is my script: 这是我的脚本:

$(document).ready(function() {
    if ($('.pageBody p img').css('float') === 'right') {
        $('.pageBody p img').addClass('float-right');
    }
});

That script works just fine with an image that has float: right applied. 该脚本对于具有float: right的图像可以float: right There is another image that has float: left applied. 还有另一个具有float: left图像:已应用float: left The problem is, if I switch "right" to "left" in the script than it wont' work. 问题是,如果我在脚本中将“ right”切换为“ left”,将无法正常工作。 For example, if I have an image set to float: left and use this script than it doesn't work: 例如,如果我将图像设置为float: left并使用此脚本,则它不起作用:

$(document).ready(function() {
    if ($('.pageBody p img').css('float') === 'left') {
        $('.pageBody p img').addClass('float-left');
    }
});

Your current code will only work if the image you're interested in is the first one in the document. 仅当您感兴趣的图像是文档中的第一个图像时,当前代码才有效。 You can use filter() to locate that image regardless of its position in the DOM: 您可以使用filter()定位该图像,而不管其在DOM中的位置如何:

$(document).ready(function() {
    $(".pageBody p img").filter(function() {
        return $(this).css("float") == "left";
    }).addClass("float-left");
});

Alternatively, you can use the form of addClass() that takes a function to add float-left or float-right classes to all the images depending on the value of their float style: 另外,您可以使用addClass()的形式,该形式采用一个函数来根据所有图像的float样式的值向所有图像添加float-left float-rightfloat-right类:

$(document).ready(function() {
    $(".pageBody p img").addClass(function() {
        var direction = $(this).css("float");
        if (direction == "left" || direction == "right") {
            return "float-" + direction;
        } else {
            return "";
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM