【问题标题】:Dynamically capture a div position动态捕获一个div位置
【发布时间】:2014-05-08 23:27:45
【问题描述】:

有没有一种方法可以显示/捕获 div 的最高值,同时它会像 Chrome 开发工具的元素选项卡一样在动画时发生变化?我试过 getComputedStyle 和 getPropertyValue 但不起作用。这是我迄今为止尝试过的

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/

【问题讨论】:

  • 尝试使用'animate'的步骤或进度api.jquery.com/animate或使用animationIteration事件css-tricks.com/…
  • 谢谢你们。这两个都回答了我的问题,我认为我必须把支票交给 Amadeus,因为他是第一个加入的人。

标签: jquery css


【解决方案1】:

您提供的代码的问题是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/

【讨论】:

    【解决方案2】:

    这是一个使用 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/

    【讨论】:

      猜你喜欢
      • 2016-05-17
      • 2022-11-23
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多