javascript get style and increment

雨燕双飞 提交于 2019-12-11 17:41:36

问题


I'm trying to make a slider that changes the margin-left attribute in the external css onclick. So I need to get the attribute and then set the new attribute.

here is my code:

<style>
#divName
 {
  margin-left:20px;
 }
</style>

    <script language="javascript" type="text/javascript">  

                var x = document.getElementById(divName);

            if (x.currentStyle)
            {
                var y = x.currentStyle[marginLeft];
            }
            else (window.getComputedStyle)
            {
                var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(marginLeft);
            }

                y = y + 20;

                document.getElementById(divName).style.marginLeft = y .'px';

    </script>

thanks for your time


回答1:


In Javascript, the . operator does not concatenate strings.

Use the + operator instead:

document.getElementById(divName).style.marginLeft = y + 'px';

You also probably need to pass marginLeft as a string, not a name (unless there is a variable in scope that is named marginLeft and set to "marginLeft"):

var y = x.currentStyle["marginLeft"];

And:

var y = document.defaultView.getComputedStyle(x, null).getPropertyValue("marginLeft");


来源:https://stackoverflow.com/questions/12880524/javascript-get-style-and-increment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!