我正在使用此代码在悬停元素并按下 shift 键时切换背景。如果我在输入元素之前按住 shift 键,它会起作用,但如果我已经在元素上并按下 shift 键,它就不会起作用。想法?谢谢!
var shiftPressed = null;
$(document).on({
keydown: function (e) {
if( e.shiftKey )
{
shiftPressed = true;
}
},
keyup: function (e) {
shiftPressed = false;
}
});
$('div').on({
mousemove: function (e) {
if( shiftPressed )
{
$(this).css('backgroundColor', 'red');
}
else
{
$(this).css('backgroundColor', '');
}
},
mouseover: function (e) {
if( shiftPressed )
{
$(this).css('backgroundColor', 'red');
}
else
{
$(this).css('backgroundColor', '');
}
},
mouseleave: function (e) {
$(this).css('backgroundColor', '');
}
}, 'span');
div {
position:absolut;
width:100px;
height:100px;
background:#999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span>TARGET</span>
</div>
最佳答案
div 无法获得焦点(默认情况下);因此,它无法捕获按键操作。
但是,如果您将 keypress
事件监听器绑定(bind)到文档,则该事件将在每次按键时触发。保持 mouseover
和 mouseleave
绑定(bind)到 div,因为它们可以用不可聚焦的元素触发。
另外,一个keyboard event不同于 mouse event ,因此您无法在鼠标悬停时访问 e
的 shiftKey
。相反,我会使用 &&
运算符来测试是否满足两个条件:shift 键和鼠标进入,将 shift 键是否被按下存储在 bool 值中并在 mouseover/mouseleave 上检查。
var shiftPressed = null; // global data
$(document).on('keyup keydown', function(e) {
shiftPressed = e.shiftKey;
updateDivs();
});
$('div').on({
mouseover: function(e) {
$(this).data('hovered', true); // element-specific data
updateDiv(this);
},
mouseleave: function(e) {
$(this).data('hovered', false); // element-specific data
updateDiv(this);
}
});
function updateDiv(div) {
if (shiftPressed && $(div).data('hovered'))
$(div).css('backgroundColor', 'red');
else
$(div).css('backgroundColor', '');
}
/** updates all divs in document */
function updateDivs() {
$('div').each(function() {
updateDiv(this);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Hello world</div>
<div>Hi world</div>
关于javascript - 如果悬停并按下shift键切换背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535657/