用于设置动态最大宽度的 JQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8183549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery For Setting A Dynamic max-width
提问by Teffi
I'm not particularly good with jQuery, so a complete code solution would be ideal.
我对 jQuery 不是特别擅长,所以一个完整的代码解决方案将是理想的。
The function will:
该函数将:
- Get the 70% width of the browser's screen.
- Convert that width into its corresponding px value
- Set the max width of the
#mainContainer
using the value got from the conversion/calculation.
- 获取浏览器屏幕 70% 的宽度。
- 将该宽度转换为其相应的 px 值
#mainContainer
使用从转换/计算中获得的值设置最大宽度。
Here is the CSS style for the container I want to set max-width
with:
这是我要设置的容器的 CSS 样式max-width
:
#mainContainer {
background-image: url(bg3.jpg);
background-repeat: repeat;
background-color: #999;
width: 70%;
padding: 0;
min-width: 940px; /* 940px absolute value of 70%. */
margin: 0 auto;
min-height: 100%;
/* Serves as a divider from content to the main container */
-webkit-border-radius: 10px;
border-radius: 10px;
}
回答by Esailija
You should be able to copy paste this inside a <script>
tag anywhere in the page where you have jQuery and it should work..
您应该能够将其复制粘贴<script>
到页面中任何有 jQuery的标签中,并且它应该可以工作。
$( document ).ready( function(){
setMaxWidth();
$( window ).bind( "resize", setMaxWidth ); //Remove this if it's not needed. It will react when window changes size.
function setMaxWidth() {
$( "#mainContainer" ).css( "maxWidth", ( $( window ).width() * 0.7 | 0 ) + "px" );
}
});
回答by nathan
Or define a function for the window.onresize
event
或者为window.onresize
事件定义一个函数
window.onresize = function() {
var newWidth = ($(window).width() * .7);
$("#mainContainer").css({
"maxWidth": newWidth
});
}
#mainContainer {
background-color: #999;
width: 70%;
padding: 0;
min-width: 30px;
/* 940px absolute value of 70%. */
margin: 0 auto;
min-height: 100%;
/* Serves as a divider from content to the main container */
-webkit-border-radius: 10px;
border-radius: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainContainer">-</div>