【问题标题】:move image by pointing to the X, Y coordinates通过指向 X、Y 坐标移动图像
【发布时间】:2013-10-24 12:43:29
【问题描述】:

我有以下代码:

var currX = 0;
var currY = 0;
var player = $('#player');
//Checks to see which key is pressed down
        $(window).on('mousedown', function(e) { 
            currX = e.offsetX;
            currY = e.offsetY;
            console.log(e.offsetX + ', ' + e.offsetY);
        });


        player.css({
            left: function(index,value) { return (value + currX + 'px'); },
            top: function(index,value) { return  (value + currY + 'px'); }
        });

图像根本不动。我console.log 输出两个偏移量,它们被正确打印出来。

谢谢!

【问题讨论】:

    标签: javascript jquery css offset


    【解决方案1】:

    您正在将 topleft 的值设置为函数。执行该代码时,将对其进行一次评估。如果您希望 player 移动,您希望在 mousedown 侦听器中执行该代码。

    【讨论】:

    • 在我的 CSS 中,#player 的位置是绝对的
    【解决方案2】:

    你应该在 mousedown 事件中应用这个 css :

    $(window).on('mousedown', function (e) {
        currX = e.offsetX;
        currY = e.offsetY;
        console.log(e.offsetX + ', ' + e.offsetY);
        player.css({
            left: currX + 'px',
            top: currY + 'px'
        });
    });
    

    FIDDLE

    【讨论】:

    • 你说得对,谢谢!但是大卫先说了同样的话,所以我会选择他的答案作为正确的答案。你得到一个赞成:)
    猜你喜欢
    • 2011-03-08
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    相关资源
    最近更新 更多