JQuery用于设置动态最大宽度

Tef*_*ffi 8 css jquery dynamic css3

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

该功能将:

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

这是我想要设置的容器的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;
}
Run Code Online (Sandbox Code Playgroud)

Esa*_*ija 29

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

});
Run Code Online (Sandbox Code Playgroud)

  • 不应该是"max-width"而不是"maxWidth"? (3认同)