【问题标题】:extract a number from a property value从属性值中提取一个数字
【发布时间】:2019-10-12 08:36:39
【问题描述】:

我正在尝试创建动画,当按下按钮时,div 必须通过更改左边距向左移动 300 像素,然后停止。

我得到左边距值,但是当我尝试从中提取 300 px 时,它说 var moveto 不是数字,而 current_left_margin 的值是 0px,我怎样才能得到这个值是一个数字, 没有像素?

这是我的完整代码:

function get_vars() {           
        elem = document.getElementById('front-slide');
    }
window.onload = get_vars;

function vb_anim() {
        var interval = setInterval(anim, 10);

        var elemstyle = window.getComputedStyle(elem);

        var elemvidth = elemstyle.width;

        var current_left_margin = elemstyle.getPropertyValue('margin-left');
        var moveto = current_left_margin - 300;
            console.log('current_left_margin= ' + current_left_margin );
            console.log('moveto= ' + moveto );
        var pos = 0;
        function anim() {
            if (pos == moveto) {
                clearInterval(interval);
            } else {
                pos--;
                elem.style.marginLeft = pos + 'px';
            }
        }
    }

【问题讨论】:

    标签: javascript string animation numbers extract


    【解决方案1】:

    应该这样做:

    var current_left_margin = parseInt(elemstyle.getPropertyValue('margin-left'));
    

    如果没有,那么:

     var current_left_margin = parseInt(elemstyle.getPropertyValue('margin-left').replace('px', ''));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多