1

My goal is to calculate the width of a fixed positioned element (top:0; left:200px;) through subtract 200px from the window size so that it fits the rest of the viewport. Therefore I used the following code but sadly it doesn't work. Hopefully someone of you guys can help me!

$(function() {
    width = ($(window).width() - 100);
    $("div").css("width", width);
})​;
4

2 回答 2

3

You don't need to rely on jQuery, actually. There is a simply CSS trick to get this done, by declaring right: 0 on that element. It forces it to stretch all the way to the right border of the viewport, naturally.

div {
    position: fixed;
    top: 0;
    left: 200px;
    right: 0;
}

See fiddle here: http://jsfiddle.net/teddyrised/2Fhue/

Update 1: OP has provided his own fiddle, so here is the one with the fix applied: http://jsfiddle.net/teddyrised/w555h/2/. I have also taken the liberty to remove height: 100% and use bottom: 0 instead, which demonstrate the same concept as using positional coordinates to forcibly stretch the dimension of the element :)

Update 2: OP has requested a jQuery-based solution (beats me why, but anyway...), and here is how it works — we perform the width calculation within an anonymous function fired when the resize event is fired on the $(window) object. The second .resize() event is chained so that it fires upon DOM ready.

$(function() {
    $(window).resize(function() {
        var width = $(this).width() - 200;
        $("#content").css("width", width);
    }).resize();
});

http://jsfiddle.net/teddyrised/w555h/4/

Comment: I typically try to avoid using jQuery (or JS) for purposes like this, when CSS can be easily used. That is because by calculating the width from that of the viewport, you will also have to listen to the .resize() event of the window, which complicates things.

于 2013-11-02T21:55:40.603 回答
0

I expanded on Terry's jQuery answer. I wouldn't typically code something like this, but I inherited a WordPress theme where the #secondary sidebar changes size dynamically, but only when the #main container > 768px. Goes without saying, #primary and #secondary are floated left ;-)

    $(window).resize(function(){

        var main = $("#main").width();
        var secondary;

        if (main > 768) {
            secondary = $("#secondary").outerWidth(true);
        } else 
            secondary = 0; // Ignore smaller dimensions where the sidebar is not visible.

        $("#primary").css("width", main - secondary - 1);

    }).resize();

    $(window).trigger('resize'); // When the page first loads
于 2019-05-21T20:52:24.770 回答