zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Monitor real-time changes to the page

The problem arises from the requirements because the project needs to adapt to multiple layouts for both PC and mobile devices, causing certain elements to be misaligned under specific widths.

If it is in CSS, it can be easily determined. By using media queries, the page width can be detected in real-time, and different attributes can be applied to the tags.

@media (max-width:768px){
    ...
}

In JavaScript, the following method can be used:

window.addEventListener('load', function() {
    window.addEventListener('resize', function() {
        console.log(window.innerWidth)
        var w = window.innerWidth;
        ...
        }
    })
})

You can try the specific details of the operation, and it is still a very good method. Also, pay attention to window because this is just an example that I wrote directly. In actual coding, use the window event with caution.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.