2014-05-08 88 views
0

有没有一种方法显示/捕获div顶部值,而它的动态变化类似于Chrome开发工具元素选项卡?我试过getComputedStyle和getPropertyValue,但不起作用。这是我迄今动态捕捉div位置

var top_sq = document.getElementById("square"), 
style_sq_top = getComputedStyle(top_sq), 
sq_top = style_sq_top.getPropertyValue("top"), 
act_sq_top = sq_top.substring(0, 3); 

var tv = document.getElementById("top_value").text = sq_top; 

$("#btn1").click(function(){ 
$("#square").animate({top:"300px"}, 3000); 
tv.toString; 
}); 

http://jsfiddle.net/QYVQT/

+0

尝试使用 - 步或进步 - 的 '动画' http://api.jquery.com/animate/或使用animationIteration事件的http:// CSS-技巧.com/controls-css-animations-transitions-javascript/ – keypaul

+2

谢谢你们。这两个都回答我的问题,我认为我必须把支票给艾玛迪斯,因为他是第一个输入。 – user35859

回答

0

与您所提供的代码的问题是,tv为箱动画不动态改变试过。请记住,sq_top只是一个数字。当您设置tv等于sq_top时,您将它设置为等于一个数字。因此,当盒子移动时,tv的值不会改变。

而是每次重新计算一次。您可以使用.animate()函数的progress属性来执行此操作。看到这里:http://www.bennadel.com/blog/1856-using-jquery-s-animate-step-callback-function-to-create-custom-animations.htm。使用$.progress()功能

代码:

var square = document.getElementById("square"), 
    squareTop = null, 
    squareTopString = null, 
    tvDiv = document.getElementById('top_value'); 

$("#btn1").click(function(){ 
    $("#square").animate(
     {top:"300px"}, 
     { 
      duration: 3000, 
      progress: function(){ 
       /* get the top of the square */ 
       squareTop = square.style.top; 
       /* format it correctly */ 
       dotLoc = squareTop.indexOf('.'); 
       if(dotLoc == -1){ 
        squareTopString = squareTop; 
       } else{ 
        squareTopString = squareTop.substring(0, dotLoc) + 'px'; 
       } 
       /* display the current top position, e.g. "200px" */ 
       tvDiv.innerHTML = squareTopString; 
      }, 
      easing: "swing" 
     } 
    ); 
}); 

而且小提琴:http://jsfiddle.net/KLhzp/3/

0

下面是一个使用jQuery animate()'s step()回调的例子。

var top_sq = document.getElementById("square"), 
    style_sq_top = getComputedStyle(top_sq), 
    sq_top = style_sq_top.getPropertyValue("top"), 
    act_sq_top = sq_top.substring(0, 3); 

var $tv = $("#top_value") 
$tv.text(act_sq_top); 

$("#btn1").click(function() { 
    $("#square").animate({ 
     top: "300px" 
    }, { 
     duration: 3000, 
     step: function (now, fx) { 
      pos = Math.round(now); 
      $tv.text(pos); 
     } 
    }); 
}); 

而这里的小提琴http://jsfiddle.net/QYVQT/2/