开发者

why the js code can't control the css code?

开发者 https://www.devze.com 2023-03-15 05:53 出处:网络
<script> var divBgTop=0; function initDivTop() { divBgTop=document.getElementById(\"divBg\").style.pixelTop;
<script>
        var divBgTop=0;
        function initDivTop()
        {
                divBgTop=document.getElementById("divBg").style.pixelTop;
                alert(divBgTop);
        }
</script>
<style>
.divBgCss
{
        position:absolute;
          left:100px;
    top:100px;
    width:100px;
    height:100px;
        background-color:red;
}
</style>
<body onload="init开发者_开发问答DivTop()">
<div class="divBgCss" id="divBg"></div>
</body>

the result is always 0. why?


What you're after is the offsetTop:

divBgTop=document.getElementById("divBg").offsetTop;

Without specifying the unit, you will not get 0 but rather something else but not 100 - you better add unit like px so you won't get wrong results when using the code.

Live test case: http://jsfiddle.net/A9Mr2/1/


There is was an error in the CSS. You specify 100, but without a unit. Make it 100px (or another unit, if you wish).

Now the only problem is the used propery. pixelTop apparently won't work, but offsetTop will. This is a property of the element, rather than the style, so you'll need: getElementById('divBg').offsetTop

[edit: adjustment and addition after question is modified]


the pixelTop property is read-only, all others are read/write. you can set the pixelTop property..like http://jsfiddle.net/bingjie2680/WJrn6/

update:sorry: write-only


I think the code should be:

divBgTop = document.getElementById("divBg").style.top;

However, this will only read inline styles. To read computed styles you need to... well... read computed styles :)

0

精彩评论

暂无评论...
验证码 换一张
取 消