JQuery用于设置动态最大宽度

我对jQuery并不是特别擅长,所以完整的代码解决方案将是理想的。

该function将:

  1. 获得浏览器屏幕宽度的70%。
  2. 将该宽度转换为其对应的px值
  3. 使用从转换/计算中获得的值设置#mainContainer的最大宽度。

这是我想要设置max-width的容器的CSS样式:

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

你应该能够在你拥有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" ); } }); 

或者为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; } 
  
-