我正在编写一个适合桌面和移动设备的网站,当然,最初的想法是使用百分比宽度,然后设置一个移动CSS样式表,如果屏幕小于700像素,则将元素宽度更改为100%。
这样做的问题是您越过障碍物时出现的“结块”。
所以我想:“为什么不添加一个jQuery调整大小脚本来流畅地调整元素的大小,以免产生麻烦?”
问题在于写方程式。
我想通了,但是现在我担心它会消耗多少处理能力。我不希望此功能落后于网站的其余部分。
这是我的jFiddle:
http://jsfiddle.net/jp685suz/1/
...以及等式:
var windowW = $(window).innerWidth();
var rangeMax = 1000; //Change occurs between 700px and 1000px
var rangeMin = 700;
var rangeDiff = 1000-700;
var minWidth = 50;
var dynWidth = Math.round(((1-(((rangeDiff-(rangeMax-windowW))/rangeDiff)/(100/(100-minWidth))))*100)*10)/10;
尝试调整窗口大小以了解我的意思。现在还不算慢,但是可以在幻灯片放映和其他jQuery功能中添加一些高分辨率的照片,但这并不完美。当然,这不是一个大问题,因为大多数人并不经常调整窗口大小,但我想炫耀。
我的方程式可以简化吗?也许jQuery内置了某些功能来执行此操作?
最佳答案
你要这个:
窗口小于100%
宽度时的700px
宽度。
窗口大于50%
宽时的1000px
宽度。
然后,您决定在700px
和1000px
之间线性减小百分比。
但是,存在一个问题:解决百分比后,使用的宽度变为
如您所见,增加窗口的宽度会减小该部分的宽度,从而产生非常奇怪的效果。
让我提出一种不同的方法:
窗口小于100%
宽度时的700px
宽度。
窗口为100% = 700px
宽时为700px
宽度。
当窗口在700px
和700px
宽度之间时,1400px
宽度。
窗口为50% = 700px
宽时为1400px
宽度。
窗口大于50%
宽时的1400px
宽度。
也就是说,使用恒定宽度700px
,并用百分比钳位它:
width: 700px;
min-width: 50%;
max-width: 100%;
section {
width: 700px;
min-width: 50%;
max-width: 100%;
margin: 0 auto;
}
section:before {
content: '';
display: block;
height: 100px;
background-color: olivedrab;
}
<section>
<p>This olive green box will be a reasonable size on a big monitor (50% of the screen), and will fill the screen (100%) if it gets smaller than 700px (i.e. mobile).</p>
<p>The transition is smooth. Go ahead, try resizing the window and see how pretty!</p>
<p>This is not as "clunky" as setting a CSS mobile screen profile, but uses jQuery which isn't always a good idea.</p>
</section>
关于javascript - 减小窗口大小时如何增加元素宽度?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34112037/