2 回答
TA贡献1830条经验 获得超3个赞
你可以用 jQuery 做到这一点。使用 child 和 each 循环遍历所有的孩子(如果需要)。并得到backgroundImage
$(".team-member").click(function() {
$(this).children().each(function () {
var background = $(this).css("backgroundImage"); // this gets the background of each child
var className = $(this).attr("class"); // this gets the class list of each child (if needed)
$(".result").append(className + " background URL is: " + background + "<br/>");
});
}) ;
.team-one {
margin-top: 15px;
background: url("../media/team-one.jpg") no-repeat 50% 50%;
background-size: cover;
}
.team-two {
background: url("../media/team-two.jpg") no-repeat 50% 50%;
background-size: cover;
}
.team-three {
background: url("../media/team-three.jpg") no-repeat 50% 50%;
background-size: cover;
}
.team-member {
background: url("../media/team-member.jpg") no-repeat 50% 50%;
background-size: cover;
}
.result {
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
<div class="team-img team-one">Team one</div>
<div class="team-img team-two">Team two</div>
<div class="team-img team-three">Team three</div>
</div>
<div class="result">
</div>
注意:您希望该功能在单击时运行,.team-member但您的选择器是member.
如果您只需要一队(或特定班级)背景,请参见下文:
$(".team-member").click(function() {
var background = $(".team-one").css("backgroundImage"); //gets background of team-one
var className = $(".team-one").attr("class"); //gets classes of team-one
$(".result").append(className + " background URL is: " + background + "<br/>");
}) ;
.team-one {
margin-top: 15px;
background: url("../media/team-one.jpg") no-repeat 50% 50%;
background-size: cover;
}
.result {
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
<div class="team-img team-one">Team one</div>
</div>
<div class="result">
</div>
TA贡献1796条经验 获得超4个赞
$(".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>
添加回答
举报