如何获取javascript中的样式属性的初始值? [英] How to get the initial value of style properties in javascript?

查看:124
本文介绍了如何获取javascript中的样式属性的初始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的HTML文件中,我有以下标记:

In my html file I have the following markup:

<div class="long_box">
    <div class="image1">  <img src="images/image1.png">  </div>
    <div class="image2">  <img src="images/image2.png">  </div>
    <div class="image3">  <img src="images/image3.png">  </div>
</div>

在css文件中,我应用了以下样式规则:

In the css file I have applied the following style rules:

.long_box {
    width: 3300px;
    height: 768px;
    position: absolute;
    left: 10px;
    top: 0;
}

在javascript文件中,我做了一个变量:

In the javascript file I made a variable as:

var longbox = document.getElementsByClassName("long_box")[0];

现在当我尝试调用 left long_box longbox.style.left ,我得到一个空字符串 。但在我用javascript改变 left 值之后,如 longbox.style.left = 100 +'px ,然后回想它的值,那么我在控制台中得到 100px

Now when I try to recall the initial value of left of long_box as longbox.style.left, I get an empty string "". But after I change the left value with javascript, e.g. as as longbox.style.left = 100 + 'px and then recall it's value then I get 100px in the console. So,

推荐答案

如何获取JavaScript中的样式属性的初始值? >

Javascripts element.style 只返回内联样式,对于其他样式,例如在样式表中设置,您必须使用 getComputedStyle

Javascripts element.style only returns inline styles, for other styles, for instance set in a stylesheet, you'd have to use getComputedStyle

var longbox = document.getElementsByClassName("long_box")[0];

var styles  = window.getComputedStyle(longbox);

var lef     = styles.getPropertyValue("left");

这篇关于如何获取javascript中的样式属性的初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆