简体   繁体   中英

Screen.width problem with content and conditions

Welcome I have simple problem with screen.width condition. It's my html code :

 <ul class="offer-image clearfix">
            <li>
                <figure class="figure-image bottom-left" >
                    <div id="fire">
                        <h3> lighting a fire!</h3>
                        -We Light a fire on evening<br>
                        -We are using only real wood<br>
                        -You will find the best pleaces for bonfire<br>
                    </div>
                    <img src="resources/img/fire-min.jpg" >
                </figure>
            </li>

I would like to change content in fire div so I've used javascript :

if (screen.width > 650) {
 document.getElementById("fire").innerHTML = "<h3> lighting a fire!</h3>";

} else if (screen.width < 650) {
    document.getElementById("fire").innerHTML = "<h3> lighting a fire!</h3>-We Light a fire on evening<br> -We are using only real wood<br>-You will find the best pleaces for bonfire<br>";
}

The main problem should be simple. When I am refreshing the page, the content is appearing from document.getElementById("fire").innerHTML and won't change content from else if condition when screen.width is higher than 650. Can somebody explain me why it doesn't work?

The screen.width returns the total width of the user's screen, in pixels so it will not change. In your case, it should be window.innerWidth instead.

use window.innerWidth instead of screen.width , the first give you the current width, the later give you the original screen width.. moreover the window.innerWidth is static value so for you to keep having you content dynamic in case your screen width changes constantly use the onresize listener like this:

        window.onresize = function(){
            if (window.innerWidth > 650) {
                document.getElementById("fire").innerHTML = "<h3> lighting a fire! grater than 650</h3>";

            } else if (window.innerWidth <= 650) {
                document.getElementById("fire").innerHTML = "<h3> lighting a fire! less than 650 </h3>-We Light a fire on evening<br> -We are using only real wood<br>-You will find the best pleaces for bonfire<br>";
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM