开发者

Set a HTML elements width attribute right away using javascript

Is it possible to set an elements width like this:

<img id="backgroundImg" src="images/background.png" alt="" width="javascript:getScreenSize()['width']+px" height="1100px"/>

Where getScreenSize() is a javascript function.

        function getScreenSize()
        {
            var res = {"width": 630, "height": 460};

            if (document.body) 
            {
                 if (document.body.offsetWidth)  res["width"]  = document.body.offsetWidth;
                 if (document.body.offsetHeight) res["height"] = document.body.offsetHeight;
            }

            if (window.innerWidth)  res["width"]  = window.innerWidth;
            if (window.innerHeight) res["height"] = window.innerHeight;
            alert( res['wi开发者_开发问答dth'] );

            return res;
        }

Or do I have to change the img's width inside a javascript function?

function changeImgWidth( img )
{
   img.offsetRight = getScreenWidth()['width'] + "px";
}


You can't do it with that syntax, no. You could use document.write to do it, but I suspect you'd be better off doing it after the DOM loads, because I think your getScreenSize function may not report correct results until then (but it may, you'll have to test).

To do it with document.write:

<script>
document.write('<img id="backgroundImg" src="images/background.png" alt="" width="' + getScreenSize()['width'] + '" height="1100px"/>');
</script>

To do it once the DOM is loaded, put this at the very end of your page, just before the closing </body> tag:

<script>
document.getElementById('backgroundImg').width = getScreenSize()['width'];
</script>

In both of those examples, I've stuck with the width attribute (note that you don't use a units suffix — "px" — with the width attribute). But you might consider using the CSS width property instead (which you would use the suffix with).


Stepping back, though, rather than relying on JavaScript to set the width, I'd recommend trying to do it with CSS. You can make the image 100% of the width of its container by using style='width: 100%' within the tag or:

#backgroundImg {
    width: 100%;
}

...in a stylesheet.


you don't need +px in the img-tag


Even if it could be done that way, it would be better not to, so you can separate content(HTML) & behavior(javascript). It's the same reason why it's better not to put

onclick='somefunction(); return false;'

inside a link, for example. Instead, if you used jQuery, for example, you could put

$('#somelink').click(function() {//do something});

inside a

$(document).ready(

block. If nothing else, you can have all the javascript in one place, instead of scattered everywhere in the markup. CSS stylesheets are better than inline styles for the same reason.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜