【问题标题】:Moving a DOM object with Javascript使用 Javascript 移动 DOM 对象
【发布时间】:2017-04-23 04:24:07
【问题描述】:

我是 javascript 新手,我只是想在鼠标悬停时移动链接。

我希望下面的代码能做到这一点。但上面写着Uncaught TypeError: Cannot set property 'left' of undefined

$('a').mouseover(function(){
    yPosition = parseInt(Math.random() * window.screen.availHeight);
    xPosition = parseInt(Math.random() * window.screen.availWidth);
    $(this).style.left = xPosition + "px";
    $(this).style.top = yPosition + "px";
});

【问题讨论】:

  • $(this) 是一个 jquery 对象。而 style 是本机 dom 属性。
  • 使用jQuery的$(this).style.left= xPosition + "px";必须是$(this).css('left', xPosition + "px");
  • @choz 是对的。您需要编写选择器并获取 DOM 元素。那就修改吧。
  • 您的问题得到解答了吗?如果是这样,请选择一个答案。
  • 从不。采用。解析整数。和。数字。

标签: javascript jquery dom typeerror


【解决方案1】:

使用 .css() 。您出现该错误的原因是:

  • .style 用于纯 JavaScript 内联样式属性。

  • $(this) 是一个 jQuery 对象,因此您应该使用 jQuery 方法,除非您取消引用它:$(selector)[0]

请务必在全页模式下查看 Snippet,链接会像散落的蟑螂一样飞散。

片段

$('a').hover(function() {
  var yPosition = parseFloat(Math.random() * window.screen.availHeight)+'px';
  console.log(yPosition);
  var xPosition = parseFloat(Math.random() * window.screen.availWidth)+'px';
  console.log(xPosition);
  $(this).css({
    left: xPosition,
    top: yPosition
  });
});
a {
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#/'>LINK</a>
<a href='#/'>LINK</a>
<a href='#/'>LINK</a>
<a href='#/'>LINK</a>
<a href='#/'>LINK</a>
<a href='#/'>LINK</a>
<a href='#/'>LINK</a>
<a href='#/'>LINK</a>
<a href='#/'>LINK</a>

【讨论】:

    【解决方案2】:

    使用 jQuery 你必须替换

    $(this).style.left = xPosition + "px"; 
    

    通过

    $(this).css('left', xPosition + "px");
    

    你可以替换两条样式线

    $(this).style.left = xPosition + "px";
    $(this).style.top = yPosition + "px";
    

    使用以下语法:

    $(this).css({ left: xPosition, top: yPosition });
    

    使用这个可以安全地省略单元px

    作为参考,请查看 jQuery API:

    http://api.jquery.com/css/

    【讨论】:

    • 感谢您的回复。我试过了,现在不再出现错误,但 'a' 对象没有移动。
    【解决方案3】:

    请将您的代码替换为以下版本。它会工作

       $('a').mouseover(function(){
        yPosition = parseInt(Math.random() * window.screen.availHeight);
        xPosition = parseInt(Math.random() * window.screen.availWidth);
        $(this).css('left', xPosition + "px");
        $(this).css('top', yPosition + "px");
       });
    

    【讨论】:

      【解决方案4】:

      $(this) 创建一个 jquery 对象,而这些对象没有 style 属性。

      尝试使用原始 DOM 属性

      this.style.left = xPosition + "px";
      this.style.top = yPosition + "px";
      

      或者如果您想使用 jQuery,请使用 .css 并一次性更改两个位置

      $(this).css({
          left: xPosition,
          top: yPosition 
      });
      

      【讨论】:

        猜你喜欢
        • 2016-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        • 2012-01-07
        • 1970-01-01
        • 1970-01-01
        • 2013-11-21
        相关资源
        最近更新 更多