如果在元素内单击鼠标,我想应用一些样式(此处为 .block
)。如果单击该元素,则通过 $(this)
获取该元素并为其设置样式。之后,当用户点击 $(this)
元素以外的元素时,我想将其改回默认样式。我如何检测鼠标是否被点击而不是 $(this)
元素。
到目前为止的 js 脚本:
$( document ).ready(function() {
// when a block is clicked get that specific block
$('.block').click(function() {
var block = $(this);
block.css('background','red');
});
//if clicked other than the block do stuff
});
最佳答案
更好的方法是使用 tabindex
和 css :focus
选择器
.container{
border:1px solid #333;
width:200px;
height:200px;
}
.block{
background-color: #ccc;
width:50px;
float:left;
height:50px;
margin:20px;
}
.block:focus{
background-color: red;
outline:none
}
<div class="container">
<div class="block" id="block1" tabindex="1">
</div>
<div class="block" id="block2" tabindex="1">
</div>
<div class="block" id="block3" tabindex="1">
</div>
<div class="block" id="block4" tabindex="1">
</div>
</div>
关于javascript - 如何检测鼠标是否被点击而不是 $(this) 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284158/