在左右按钮上连续移动框

Move box Continously on left and right button

本文关键字:移动 连续 左右 按钮      更新时间:2023-09-26

试图在按钮上左右移动.popup类不断从左到右和从右到左移动。

这是js小提琴。

.HTML:

<button class="right">Right</button>
<button class="left">Left</button>
<div class="popup">
    Popup
</div>

你错过了.popupdiv的左属性

 .popup {
    width: 200px;
    height: 50px;
    border: 1px dashed #000;
    position: absolute;
    top: 100px;
    left:0px;
 }

您可以按如下方式改进脚本:

$(document).ready(function () {
    var left = parseInt($(".popup").css('left'));
    var refreshIntervalId;
    $(".left").on('mousedown', function () {
        refreshIntervalId = setInterval(function () {
            $('#counter').html(parseInt($('#counter').html()) + 1);
            left += 5;
            $(".popup").css({"left": left})
        }, 10);
    })
    $(".left").on('mouseup', function () {
        clearInterval(refreshIntervalId);
    })
    $(".right").on('mousedown', function () {
        refreshIntervalId = setInterval(function () {
            $('#counter').html(parseInt($('#counter').html()) - 1);
            left -= 5;
            $(".popup").css({"left": left});
        }, 10);
    })
    $(".right").on('mouseup', function () {
        clearInterval(refreshIntervalId);
    })
});