javascript - 使用 Javascript/PHP : Trying to display background image - logic wrong?

标签 javascript php html css wordpress

因此,如果屏幕尺寸为最小,我想在 hero-wrapper div 中使用 css 显示背景图片(即 wordpress post 中的缩略图)。 900 像素。

我使用 php 检查是否有缩略图,然后使用 javascript 检查屏幕宽度,然后将 background-image 属性添加到 dive。不行,我觉得我的逻辑有问题??

HTML

    <?php
        if ( has_post_thumbnail() ) { ?>
            <?php    $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>

            <script type="text/javascript">
                if (jQuery(window).width() == 900) {
                 <?php echo '<section class="hero-wrapper" style="background-image: url(' . $thumb['0']. ') >'; ?>
                }
            </script>   
    <?php } ?>  
    <section class="hero-wrapper">

        <figure class="frontpage-hero">
            <div class="banner-box">
                <h2>GET YOUR FREE CASE ASSESSMENT?</h2>
                <h6>Enter your details below for a consultation</h6>
                <form>
                    <input type="text" name="name" placeholder="Name..">
                    <input type="text" name="email" placeholder="Email..">
                    <input type="submit" name="submit">
                </form>     
            </div>           
        </figure>

    </section>

CSS

.hero-wrapper {
    margin: 0;
    padding: 0;
    min-height: 669px;
    background-repeat: no-repeat;
}
@media screen (min-width: 900px) {
    .hero-wrapper {
        min-height: 669px;
        background-repeat: no-repeat;
    }
}

最佳答案

您正在回显 <section> <script> 内的标签标签。 你应该改变这个

<script type="text/javascript">
            if (jQuery(window).width() == 900) {
             <?php echo '<section class="hero-wrapper" style="background-image: url(' . $thumb['0']. ') >'; ?>
            }
        </script>

像这样

<script type="text/javascript">
            if (jQuery(window).width() >= 900) {
             $('.hero-wrapper').css('background-image', 'url(' + <?php echo $thumb['0']; ?> + ')');
            }
        </script>

关于javascript - 使用 Javascript/PHP : Trying to display background image - logic wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46825513/

相关文章:

php - file_get_contents() 是否使用缓存?

css - 在同一行显示图标和文本

html - 如何动态设置div高度值?

javascript - 使 HTML 背景总是变化

javascript - 键值对列表到数组数组

javascript - 有没有办法在没有全局变量的情况下取消 requestAnimationFrame ?

javascript - JavaScript 中的 ValidatorValidate 方法不适用于 ie10

php - Laravel 5.1 - Facebook 通过 Socialite(客户端错误 : 400)

php - 防止 php 类被扩展

jquery - 如何使 jQuery 与移动设备一起工作