简体   繁体   English

使用变量来定义javascript / jquery中的位置

[英]using a variable to define position in javascript/jquery

I'm testing out some code for making names float around randomly. 我正在测试一些使名称随机浮动的代码。 My general question is how do we apply variables to style attributes? 我的一般问题是如何将变量应用于样式属性? My specific example is as follows. 我的具体示例如下。 First I tried this: 首先,我尝试了这个:

<body>
Is this it?
<button id="go">&raquo; Run</button>
<div id="floatName" style="left:50px; top:150px">James</div>
<div id="n2">Sarah</div>

<script>$( "#go" ).click(function() {
  $( "#floatName" ).animate({
    left: "100px",
    top: "200px"
  }, 500, function() {
    // Animation complete.
  });
  $( "#2" ).animate({
    left: "300px",
    top: "20px"
  }, 500, function() {
    // Animation complete.
  });
});
</script>

</body>

This works as I expected. 这按我预期的那样工作。 Next I wanted to randomize the animation to that the left and top change. 接下来,我想将动画随机化为左侧和顶部的变化。 However, I don't know how to do this. 但是,我不知道该怎么做。 One try looks like this: 一种尝试如下所示:

  $( "#floatName" ).animate({
    x = Math.random()*500
    y = Math.random()*500
    left: x + "px",
    top: y + "px"
  }, 500, function() {
    // Animation complete.
  });

Obviously didn't work and I'm having problems finding the solution. 显然没有用,我在寻找解决方案时遇到了问题。

http://jsfiddle.net/veqne72f/ http://jsfiddle.net/veqne72f/

 $( "#floatName" ).animate({
   left: Math.random()*500 + "px",
    top: Math.random()*500 + "px"
  }, 500, function() {
   // Animation complete.
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM