简体   繁体   English

检测屏幕宽度以呈现断点的适当图像

[英]Detect screen width to render appropriate images for breakpoints

So I know it's not possible to grab the screen width using PHP, but I wanted to see what would be the cleanest way that I can "Check breakpoints" and then pass in the appropriate call?所以我知道使用 PHP 获取屏幕宽度是不可能的,但我想看看我可以“检查断点”然后传入适当的调用的最干净的方法是什么?

So I have this function:所以我有这个功能:

function get_featured_image($post_id) {
    $thumbnail = get_field('featured_image_mobile', $post_id);
    if (strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android') && ($thumbnail)) {
        echo '<img src="' . $thumbnail['sizes']['medium'] . '" alt="" class="imagery featured-image-selection"/>';
    } else if (has_post_thumbnail($post_id)) {
        echo '<img src="' . get_the_post_thumbnail_url() . '" alt="" class="imagery featured-image-selection"/>';
    }
}

I'm checking the user_agent on whether it's mobile or not and outputting a img src using ACF, otherwise if it's desktop and has the thumbnail, use that, but it's not the most reliable in determining sizing since the mobile view on desktop comes back as "desktop" still.我正在检查 user_agent 是否是移动的,并使用 ACF 输出 img src,否则如果它是桌面并且有缩略图,请使用它,但它在确定大小方面并不是最可靠的,因为桌面上的移动视图返回为仍然是“桌面”。

Is there a cleaned way that I can detect "breakpoints" so that I can use the $thumbnail['sizes']['medium'] up until like 700px and then use get_post_thumbnail_url() with anything above 700px in width?有没有一种干净的方法可以检测“断点”,以便我可以使用$thumbnail['sizes']['medium']直到 700px,然后使用宽度超过 700px 的get_post_thumbnail_url()

I don't know if your goal is to use just PHP but the easiest way is to use CSS.我不知道您的目标是否只是使用 PHP,但最简单的方法是使用 CSS。 These are basic media queries, you can change them as you want.这些是基本的媒体查询,您可以根据需要更改它们。

// For small devices
@media (min-width: 576px) {
    .imagery {
        background-image: url("images/thumbnail-small.jpg");
    }
}
// For medium devices
@media (min-width: 768px) {
    .imagery {
        background-image: url("images/thumbnail-medium.jpg");
    }
}
// For large devices
@media (min-width: 992px) {
    .imagery {
        background-image: url("images/thumbnail-large.jpg");
    }
}
// For larger devices
@media (min-width: 1200px) {
    .imagery {
        background-image: url("images/thumbnail-larger.jpg");
    }
}

I got a reference from Bootstrap's page but there are lots of pages and examples.我从Bootstrap 的页面上得到了一个参考,但有很多页面和示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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