猿问

jQuery:单击时我需要选择元素的背景属性

使用 jQuery,单击此.team-member容器时...


<div class="team-member">

    <div class="team-img team-one"></div>

</div>

...我想获取设置为.team-one...的背景网址


.team-one {

    background: url("../media/team-one.jpg") no-repeat 50% 50%;

    background-size: cover;

}

这是我所得到的,它返回了正确的类,但我不能更进一步。甚至可以通过这种方式获取元素的背景属性,还是我需要做其他事情?


$(".member").click(function(member) {

    console.log(member.currentTarget.children[0].children[0].classList[1])

})  


慕勒3428872
浏览 167回答 2
2回答

牛魔王的故事

你可以用 jQuery 做到这一点。使用 child 和 each 循环遍历所有的孩子(如果需要)。并得到backgroundImage$(".team-member").click(function() {&nbsp; &nbsp; &nbsp; &nbsp; $(this).children().each(function () {&nbsp; &nbsp; var background = $(this).css("backgroundImage"); // this gets the background of each child&nbsp; &nbsp; var className = $(this).attr("class"); // this gets the class list of each child (if needed)&nbsp; &nbsp; $(".result").append(className + " background URL is: " + background + "<br/>");});}) ;.team-one {&nbsp; &nbsp; margin-top: 15px;&nbsp; &nbsp; background: url("../media/team-one.jpg") no-repeat 50% 50%;&nbsp; &nbsp; background-size: cover;}.team-two {&nbsp; &nbsp; background: url("../media/team-two.jpg") no-repeat 50% 50%;&nbsp; &nbsp; background-size: cover;}.team-three {&nbsp; &nbsp; background: url("../media/team-three.jpg") no-repeat 50% 50%;&nbsp; &nbsp; background-size: cover;}.team-member {&nbsp; &nbsp; background: url("../media/team-member.jpg") no-repeat 50% 50%;&nbsp; &nbsp; background-size: cover;}.result {&nbsp; margin-top: 15px;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="team-member">Team Member&nbsp; &nbsp; <div class="team-img team-one">Team one</div>&nbsp; &nbsp; <div class="team-img team-two">Team two</div>&nbsp; &nbsp; <div class="team-img team-three">Team three</div></div><div class="result"></div>注意:您希望该功能在单击时运行,.team-member但您的选择器是member.如果您只需要一队(或特定班级)背景,请参见下文:$(".team-member").click(function() {&nbsp; &nbsp; var background = $(".team-one").css("backgroundImage"); //gets background of team-one&nbsp; &nbsp; var className = $(".team-one").attr("class"); //gets classes of team-one&nbsp; &nbsp; $(".result").append(className + " background URL is: " + background + "<br/>");}) ;.team-one {&nbsp; &nbsp; margin-top: 15px;&nbsp; &nbsp; background: url("../media/team-one.jpg") no-repeat 50% 50%;&nbsp; &nbsp; background-size: cover;}.result {&nbsp; margin-top: 15px;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="team-member">Team Member&nbsp; &nbsp; <div class="team-img team-one">Team one</div></div><div class="result"></div>

SMILET

$(".team-member").click(function(){const backGround = $(this).closest(".team-one").attr('style').split(";")[0];console.log(backGround);});<div class="team-img team-one" style="background: url("../media/team-one.jpg") no-repeat 50% 50%;background-size: cover;"></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答