簡體   English   中英

從寬度更改div:100%; 到寬度:1000像素; 當<1000px(Javascript)

[英]Change div from width: 100%; to width: 1000 px; when <1000px (Javascript)

我正在尋找僅當瀏覽器的寬度<1000px時將div寬度從100%更改為1000px的正確的Javascript(而非JQuery)代碼。 如果瀏覽器大小> 1000px,則代碼將變回100%。 我決心在學習JQuery之前先學習JavaScript! 我可以找到很多JQuery解決方案,但想學習JS! 在小提琴中,我想更改名為“ red”的div元素。 原因是因為min-width:1000px; 在ie中不受支持,因此我需要一個可行的解決方案。 非常感謝您的幫助。 鏈接到小提琴在這里: http : //jsfiddle.net/Margate/ddENL/

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>
<title>Positioning</title>

<style type="text/css"> 
#red {position: absolute; margin-top: 100px; width: 100%; min-width: 1000px; height: 400px; background-color: red;} 
#contents {position: relative; top: 10px; width: 1000px; height: 600px; margin: 0px auto; border: 1px solid white;} 
html, body, div {margin: 0; padding: 0; border: 0;}
</style>

</head>

<body style="background-color: black;">

<div id="red"></div>
<div id="contents"></div>
</body>

</html>

嘗試這個

window.onload = function() {
    var browserWidth = document.body.clientWidth;
    if(browserWidth < 1000) {
        document.getElementById('red').style.width = '1000px';
    }
};

對於較舊的ie,您可以在標頭,外部文件中使用javascript或在CSS中使用expression

然后,它允許將javascript插入IE只能理解的CSS文件中。

基准線是:

 = document.body.clientWidth < 1001 ? "100px" : "auto"

在CSS文件中

width: expression( document.body.clientWidth < 1001 ? "100px" : "auto" ); /* set min-width for IE */

像這樣的東西: http : //jsfiddle.net/ddENL/1/

detectResize();
window.onresize = detectResize;

function detectResize(){
    var redElement = document.getElementById("red");
    var windowWidth = window.innerWidth;

    if (windowWidth < 1000){
        redElement.innerHTML = "Less than 1000";
    } else {
        redElement.innerHTML = "More than 1000";
    }
}
var ObjRedDiv=document.getElementById('red');  

/** Get Width Of the browser **/
var browserWidth=window.innerWidth || document.body.clientWidth; 

if(browserWidth<1000) 
{
    ObjRedDiv.style.width='1000px';
}
else
{
    ObjRedDiv.style.width='100%';
}

JavaScript的:

window.onresize = function() {
    var widthViewport = window.innerWidth || document.body.clientWidth;
    var el = document.getElementById('red');

    if( widthViewport < 1000 ) {
        // Append the classname which specifies the fixed width
        el.className += ' fixed_width';
    } else {
        // Remove the classname that fixes the width at 1000px
        el.className = el.className.replace( /(\b\s*fixed_width\b)+/, '' );
    }
};

CSS:

.fixed_width{
    width: 1000px;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM