从属性值中提取数字

问题描述 投票:0回答:1

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

我得到了左边距值,但是当我尝试从中提取300 px时,它说var moveto不是数字,而current_left_margin的值是0px,我怎样才能将此值变成数字,没有px?

这是我的完整代码:

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个回答
0
投票

这应该做:

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

如果不是,则:

 var current_left_margin = parseInt(elemstyle.getPropertyValue('margin-left').replace('px', ''));
© www.soinside.com 2019 - 2024. All rights reserved.