开发者

How to gracefully degrade a 100% image on a DIV with JavaScript off

The previous question I asked about creating a DIV where size is calculated from height x width of viewport is answered 开发者_运维技巧very well here: Square DIV where height is equal to viewport

I have a background image applied to the #square DIV that fits and resizes beautifully when JavaScript is on. However when JavaScript is OFF, the background image stretches to a width of 100% of the viewport- I presume because the #square div isn't being fed any information about how wide it should be, and is defaulting to 100%.

So my question is: what approaches could I use so that this doesn't happen? Can I feed my #square DIV a default-width in case JavaScript is OFF, but which is overridden when JavaScript is ON?

Here is the JQuery (thanks to the answer on the previous question):

$(document).ready(function(){
    var height = $(window).height();
    $('#square').css('height', height);
    $('#square').css('width', (height*1.1));
});

Here is the CSS:

html, body, img {
    height: 100%;
    margin: 0;
    border: 0;
    padding: 0;
}

#container {
    width: 100%;
    height: 100%;
    min-width: 500px;
    min-height: 500px;
    background-color: #e0aa0e;
}

#square {
    min-width: 500px;
    min-height: 500px;
    overflow: hidden;
    background-image:url('images/bg.png');
    background-repeat: no-repeat;
    background-size:cover;
}

and here is the HTML:

<div id="container">
    <div id="square">
        Content within square
    </div>
</div>

What I am trying to do is create a liquid, resizable page with information elements arranged over different regions of the background image of #square- so I am basing all element sizing off the size of #square. Which, since #square is getting it's sizing from JQuery, doesn't work with JavaScript off. Am happy for the no-JQuery view to be static rather than liquid. Thanks in advance for all suggestions.


You could put a CSS class on the #square div which has an absolute width and height set, and then in your jQuery script, use removeClass() on #square to remove that CSS class. Thus with no jQuery available, it'd be that set width and height, and then if jQuery is enabled, it becomes liquid.

#square {
    min-width: 500px;
    min-height: 500px;
    overflow: hidden;
    background-image:url('images/bg.png');
    background-repeat: no-repeat;
    background-size:cover;
}

#square.nojavascript {
    width: 960px;
    height: 960px;
}

<div id="square" class="nojavascript">

$('#square').removeClass('nojavascript');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜