簡體   English   中英

使用jQuery左右移動圖像

[英]Moving image left and right with jQuery

好的,這是更新的工作代碼。 使圖像具有相對性就可以了。 現在剩下的唯一事情就是,一旦我從鑰匙上移開手指,我就希望圖像停止移動。 我如何正確使用鍵盤?

<html>
<head></head>
<body>
        <img id="pic" src="run0.png" alt="image" height="100" width="100" style="position: relative;"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script> 

$(document).keydown(function(event){
     var keycode = (event.keyCode ? event.keyCode : event.which);                
                if(keycode == '39'){
                    $("#pic").animate({
                         left: '+=10px',
                    });
                }
     });

</script>
    </body>
</html>

我也不想不必先使用HTML將圖像放在文檔上,而只是將其從Javascript / jQuery附加到文檔中。 如果有人可以幫助我使用純Javascript做到這一點,將不勝感激。

按鍵無法檢測到箭頭鍵。 閱讀: 在JavaScript中檢測箭頭鍵的按下

同樣,為使left屬性影響圖像,也應絕對將其放置在頁面中。 這是一個示例演示: https : //jsfiddle.net/6haxsbz9/

HTML:

<img id="pic" src="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="image" width="100" />

CSS:

img {
    position:absolute;
    left:10px;
    top:10px;
}

JS:

$(function () {

    $(document).keydown(function (event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '39') {
            $("#pic").animate({
                left: '+=5px',
            });
        }
    });

});

首先,如評論中所述,修復語法錯誤!

然后,您要使用left在CSS position的CSS屬性為圖片設置動畫。 如果將其添加到圖像中,它將可以正常工作(我只是將鍵碼97用作a因為我不知道39是什么):

HTML:

<img id="pic" src="run0.png" alt="image" height="100" width="100" />

CSS:

#pic {
    position: absolute;
    left: 20px;
}

jQuery的:

$(document).keypress(function (event) {
    // var keycode = (event.keyCode ? event.keyCode : event.which);

    console.log(event.keyCode);
    if (event.keyCode == '97') {
        $("#pic").animate({
            left: '+=5px',
        });
    }
});

參見jsfiddle: https ://jsfiddle.net/914m6ut3/

嘗試為圖像添加相對位置:

<img id="pic" src="run0.png" alt="image" height="100" width="100" style="position: relative;"  />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM