热门关键字:
jquery > jquery教程 > jquery教程 > 使用jQuerykeydown方法

使用jQuerykeydown方法

340
作者:管理员
发布时间:2021/2/6 14:24:20
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=3909
您可以将jQuerykeydown()方法与该animate()方法结合使用,以<div>通过按键盘上的相应箭头键在左,右,上和下方向移动元素。让我们看一个例子,看看它是如何工作的:


例试试这个代码»
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Move DIV Element with Arrow Keys</title>
<style>
    .box{
        width: 100px;
        height: 100px;
        position: relative;
        margin: 200px auto 0;
        background: yellowgreen;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).keydown(function(e){
    switch (e.which){
    case 37:    //left arrow key
        $(".box").finish().animate({
            left: "-=50"
        });
        break;
    case 38:    //up arrow key
        $(".box").finish().animate({
            top: "-=50"
        });
        break;
    case 39:    //right arrow key
        $(".box").finish().animate({
            left: "+=50"
        });
        break;
    case 40:    //bottom arrow key
        $(".box").finish().animate({
            top: "+=50"
        });
        break;
    }
});
</script>
</head>
<body>
    <p><strong>Note:</strong> Click inside the viewport and press the arrow keys to move the box.</p>
    <div class="box"></div>
</body>
</html>





如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:jQuery
友荐云推荐