动态捕获div位置 [英] Dynamically capture a div position
问题描述
是否有一种方法可以显示/捕获divs最高值,同时它会随着动画的变化而变化(类似于Chrome开发者工具的元素"标签)?我已经尝试过getComputedStyle和getPropertyValue,但是不起作用.这是我到目前为止尝试过的
Is there a way to display/capture a divs top value while it changes as it is being animated similar to the Chrome dev tools Elements tab? I have tried getComputedStyle and getPropertyValue but doesn't work. This is what I have tried so far
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;
});
推荐答案
您提供的代码存在的问题是tv
不会随着动画盒的变化而动态变化.请记住,sq_top
只是一个数字.当将tv
设置为等于sq_top
时,就是将其设置为等于数字.因此,tv
的值不会随着框的移动而改变.
The problem with the code you've provided is that tv
does not change dynamically as the box is animated. Remember, sq_top
is simply a number. When you set tv
equal to sq_top
, you're setting it equal to a number. Thus the value of tv
doesn't change as the box moves.
相反,每次都要重新计算.您可以使用.animate()
函数的progress
属性来执行此操作.参见此处:
Instead, recalculate it each time. You can use the progress
property of the .animate()
function to do this. See here: 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/
这篇关于动态捕获div位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!