html代码:
<body style="padding: 80px; z-index: -2">
<div class="reaction" style="border-radius: 50%; background-color: blue; width: 40px; height:40px; z-index: 1">
<div class="" style="position:absolute; border-radius: 50%; background-color: purple; width: 40px; height:40px; z-index: 0;"></div>
<div class="circle" style="position:absolute; border-radius: 50%; background-color: skyblue; width: 40px; height:40px; z-index: 0"></div>
</div>
</body>
运行良好的 jQueryCODE:
$('.reaction').mousedown(function () {
$(this).find('div').css('left', '70%');
});
此代码似乎运行良好,但是
更糟糕的 jQueryCODE:
$('.reaction').mousedown(function () {
$(this).find('div.circle').css('left', '70%');
});
This Worse CODE 也可以工作,但它使 div.circle
的大小从元素中的 40*40
变为 0*0
tap浏览器开发者工具。 (style="left: 70%;"
似乎运行良好)
为什么 .circle
的大小在 Worse working jQueryCODE
之后变为 0 * 0?
最佳答案
两个代码都运行良好。没有更糟糕的代码。问题是
$(this).find('div')
.... 它针对 .reaction
中的两个 div,这就是为什么两个 div 都得到 left:70%
$(this).find('div.circle')
...它只针对具有 circle 类的 div。
堆栈片段
$('.reaction').mousedown(function() {
$(this).find('div').css('left', '70%');
$(this).find('div.circle').css('left', '30%');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body style="padding: 80px; z-index: -2">
<div class="reaction" style="border-radius: 50%; background-color: blue; width: 40px; height:40px; z-index: 1">
<div class="" style="position:absolute; border-radius: 50%; background-color: purple; width: 40px; height:40px; z-index: 0;"></div>
<div class="circle" style="position:absolute; border-radius: 50%; background-color: skyblue; width: 40px; height:40px; z-index: 0"></div>
</div>
</body>
关于javascript - 如何使用 jQuery find() 更改 css?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485113/