jQuery-通过从窗口大小中减去像素来计算元素宽度 [英] jQuery - calculate element width through subtract pixel from window size

查看:237
本文介绍了jQuery-通过从窗口大小中减去像素来计算元素宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是通过从窗口大小中减去200px来计算固定位置元素的宽度(顶部:0;左侧:200px;),以使其适合视口的其余部分.因此,我使用了以下代码,但遗憾的是它不起作用.希望你们中有人能帮助我!

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);
})​;

推荐答案

实际上,您不需要依赖jQuery.有一个简单的CSS技巧可以通过在该元素上声明right: 0来完成此任务.它迫使它自然地一直延伸到视口的右边界.

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;
}

在此处查看小提琴: http://jsfiddle.net/teddyrised/2Fhue/

更新1: OP提供了他自己的小提琴,因此这里是已应用此修复程序的小提琴: http://jsfiddle.net/teddyrised/w555h/2/.我还自由地删除了height: 100%并改用了bottom: 0,这表明了与使用位置坐标来强制拉伸元素尺寸相同的概念:)

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 :)

更新2: OP已经请求了基于jQuery的解决方案(击败了我,但无论如何……),这就是它的工作原理—我们在触发的匿名函数中执行宽度计算在$(window)对象上触发resize事件时.第二个.resize()事件被链接起来,以便在DOM准备就绪时触发.

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/

评论:在可以轻松使用CSS的情况下,我通常会尝试避免将jQuery(或JS)用于此类目的.这是因为通过从视口的宽度计算宽度,您还必须侦听窗口的.resize()事件,该事件使事情变得复杂.

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.

这篇关于jQuery-通过从窗口大小中减去像素来计算元素宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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