如何检测移动浏览器(PHP / Javascript),然后更改图像/文本?

问题描述:

Using wordpress for my new site, and I am putting together the content of my pages. But I'm struggling to come up with a way to detect a mobile browser, and then with the result, change the visibility of certain elements (text / images) on the page depending on whether it is being viewed from a mobile device or a computer.

Eg. If onmobile=true, , else .

Thanks in advance :)

使用wordpress为我的新网站,我正在整理我的网页内容。 但是我很难想出一种方法来检测移动浏览器,然后根据结果,改变页面上某些元素(文本/图像)的可见性,具体取决于是从移动设备查看还是从 计算机 p>

EG。 如果onmobile = true,则为。 p>

提前致谢:) p> div>

Likely, you'll want to differentiate between screen sizes, rather than whether or not it's a mobile browser.

As commented, you'll be better off using css media queries. One of the existing css frameworks, such as bootstrap, can be a good way to achieve this, but you don't have to use a framework.

@media (max-width: 1024px) {
    div.myClass {
        display: none;
    }
}

Will make an item hidden on small screens (including mobile devices).

@media (min-width: 1024px) {
    div.myClass {
        display: none;
    }
}

Will make something hidden on large screens. From there, mix and match to achieve whatever effect you're after.

On bootstrap, you've got helper-classes such as visible-md-block and hidden-xs to fine-tune visibility on various screen sizes. See Bootstrap docs for more info on that bit.

You can check for a mobile browser and edit by:

CSS:

#show{display:none;}

Javascript

function check{
    if(window.innerWidth <= 800 && window.innerHeight <= 600) {
        document.getElementById('#show').style.display= 'block' ;     
    } }