Use a DIV's width in If statement in Php file

北城余情 提交于 2019-12-23 05:07:35

问题


I have a .php file in which I have a layout that I would like to change depending of a div's width. That div is a parent of the following code and is situated in a other file.

<?php if ($(".container").width() > 400) { ?>

    <div class="sub-container">
        <div">sidepanel-left</div>
        <div>content</div>
        <div>sidepanel-right</div>
    </div>

<?php } else { ?>

    <div class="sub-container">
        <div>sidepanel-left
                <div>sidepanel-right</div>
        </div>
        <div>content</div>
    </div>

<?php } ?>

That gives me a blank page with only Html, head and body tags.

I'm sure it's a pretty basic code that I need, but I'm just starting in PHP/JS and I'm not sure of what I'm doing -_-

Let me know if you need more information!

Thanks in advance for the help! :)

B.


回答1:


You can not do this in PHP. What you can do is the following:

From PHP side, output this HTML code:

    <div class="container">
        ...
        <div class="sub-container">
            <div>sidepanel-left</div>
            <div>content</div>
            <div>sidepanel-right</div>
        </div>

    </div>

Then in your HTML page, make sure jquery is loaded, and put this:

    <script type="text/javascript">
    $(document).ready(function() { 

        $('.container').each(function(){
            var $this = $(this);
            if ( $this.width() > 400 ) {
                $this.addClass('wide-container');
            }
        });
    }); 
    </script>

Then, in your css file you can setup a class for regular container and wide container, and you can also control the styles of subcontainers:

    .container {
        // default styles here
    }

    .container.wide-container {
        // override wide container styles
    }

    .container.wide-container > .subcontainer {
        // override subcontainer styles
    }

You might use @media queries to achieve similar result, but @media queries can be applied according to the width of the screen, not a particular container.



来源:https://stackoverflow.com/questions/34275759/use-a-divs-width-in-if-statement-in-php-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!