php Javascript在PHP变量中获取屏幕宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19186243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:59:20  来源:igfitidea点击:

Javascript to get screen width in PHP variable

javascriptphp

提问by ScottD

I have a responsive site that has a simple drop-down login menuwhen the site is in a "desktop" view (screen available width > 768) next to other navigational links. When the screen width drops below 768 the navigational links end up in a select option. The problem is that the drop-down login menu doesn't work from within a select option.

我有一个响应式站点,当站点位于其他导航链接旁边的“桌面”视图(屏幕可用宽度 > 768)时,它有一个简单的下拉登录菜单。当屏幕宽度低于 768 时,导航链接最终会出现在一个选择选项中。问题是下拉登录菜单在选择选项中不起作用。

I would like to use PHP to change the drop-down login menu to a simple <a href>link when the screen width gets smaller than 768.

<a href>当屏幕宽度小于768时,我想使用PHP将下拉登录菜单更改为简单链接。

Right now I have in my page <head>:

现在我的页面中有<head>

<?
$screenWidth = '<script type="text/javascript">document.write(screen.availWidth);</script>';
?>

In the <body>:

<body>

<?
if($screenWidth <= "768") {
echo '<li><a href="login.php">Log in</a></li>';
} else {
?>
<div id="fancy">
<li id="login">
<a id="login-trigger" href="#">Log in <span>&#x25BC;</span></a>
<div id="login-content">
    <form>
        <fieldset id="inputs">
            <input id="username" type="email" name="Email" placeholder="Your email address" required>   
            <input id="password" type="password" name="Password" placeholder="Password" required>
        </fieldset>
        <fieldset id="actions">
            <input type="submit" id="submit" value="Log in">
            <label><input type="checkbox" checked="checked"> Keep me signed in</label>
        </fieldset>
    </form>
</div>                     
</li>
<? } ?>

On my desktop, I have echoed the $screenWidth, which gives 1920. Therefore I would expect the "fancy" drop-down login menu to be displayed. (And it does).

在我的桌面上,我回显了 $screenWidth,它给出了 1920。因此我希望显示“花哨的”下拉登录菜单。(而且确实如此)。

On my mobile, the $screenWidth echo gives 320. I would then expect the <a href>link to be displayed. (It does not - instead it displays the "fancy" menu).

在我的手机上,$screenWidth 回显给出 320。然后我希望<a href>显示链接。(它没有 - 而是显示“花式”菜单)。

It seems odd that the variable when echoed in the body will give a different number, but when compared in the if statement it does not change the output.

变量在正文中回显时会给出不同的数字,这似乎很奇怪,但是在 if 语句中进行比较时,它不会改变输出。

Is there a better way of changing the output?

有没有更好的方法来改变输出?

Edit: jquery responsive menu code

编辑:jquery 响应式菜单代码

jquery.responsivemenu.js:

jquery.responsivemenu.js:

(function($) {
$.fn.responsiveMenu = function(options) {
    var defaults = {autoArrows: false}
    var options = $.extend(defaults, options);
    return this.each(function() {
        var $this = $(this);
        var $window = $(window);
        var setClass = function() {
            if ($window.width() > 768) {$this.addClass('dropdown').removeClass('accordion').find('li:has(ul)').removeClass('accorChild');}
            else {$this.addClass('accordion').find('li:has(ul)').addClass('accorChild').parent().removeClass('dropdown');}
        }
        $window.resize(function() {
            setClass();
            $this.find('ul').css('display', 'none');
        });
        setClass();
        $this
            .addClass('responsive-menu')
            .find('li.current a')
            .live('click', function(e) {
                var $a = $(this);
                var container = $a.next('ul,div');
                if ($this.hasClass('accordion') && container.length > 0) {
                    container.slideToggle();
                    return false;
                }
            })
            .stop()
            .siblings('ul').parent('li').addClass('hasChild');
        if (options.autoArrows) {
            $('.hasChild > a', $this)
            .find('strong').append('<span class="arrow">&nbsp;</span>');
        }
    });
}
})(jQuery);

采纳答案by Barryrowe

Your simplest option might be to populate both options in the DOM, then use CSS3 Media queries to hide/show the proper element based on screen size.

您最简单的选择可能是在 DOM 中填充这两个选项,然后使用 CSS3 媒体查询根据屏幕大小隐藏/显示适当的元素。

So your HTML might look like:

所以你的 HTML 可能看起来像:

          <li class="login-link"><a href="login.php">Log in</a></li>
          <div id="fancy">
          <li id="login">
            <a id="login-trigger" href="#">Log in <span>&#x25BC;</span></a>
            <div id="login-content">
                <form>
                    <fieldset id="inputs">
                        <input id="username" type="email" name="Email" placeholder="Your email address" required>   
                        <input id="password" type="password" name="Password" placeholder="Password" required>
                    </fieldset>
                    <fieldset id="actions">
                        <input type="submit" id="submit" value="Log in">
                        <label><input type="checkbox" checked="checked"> Keep me signed in</label>
                    </fieldset>
                </form>
            </div>                     
        </li>

And your CSS could look like:

你的 CSS 可能看起来像:

.login-link, #login{
    display: none;
}
@media screen and (max-width: 767px){
    .login-link {
         display: block;
    }
    #login{
         display: none;
    }
}
@media screen and (min-width: 768px) {
    #login{
         display: block;
    }
    .login-link{
         display: none;
    }
}

Edit: Fixed #login reference. Edit 2: Adding JSFiddle Example JSFiddle Example

编辑:固定#login 参考。编辑 2:添加 JSFiddle 示例JSFiddle 示例

回答by Simone M

PHP is server side executed, this means that var screenWidth contains exactly: "document.write(screen.availWidth);" when you compare it. Your output is executed on client side..

PHP 在服务器端执行,这意味着 var screenWidth 正好包含:“document.write(screen.availWidth);” 当你比较的时候。您的输出在客户端执行..

回答by Halcyon

To make a responsive design, in the past, we'd use JavaScript. Since CCS3 you can use @mediato respond to changes in the viewport.

为了进行响应式设计,过去我们会使用 JavaScript。从 CCS3 开始,您可以@media用来响应视口中的变化。

Like:

喜欢:

@media screen and (max-width: 1280px) and (max-height: 1024px) {
    .splash {
        width: 100px;
    }
}
@media screen and (min-width: 1281px) and (max-width: 1920px) and (max-height: 960px) {
    .splash {
        width: 300px;
    }
}

回答by Snowburnt

Some thoughts:

一些想法:

I don't think the PHP can interact directly with the desktop like that.

我不认为 PHP 可以像那样直接与桌面交互。

Best bet is to have the client send you the response via javascript. Do an immediate postback to the same page with the screen size variable included in the header, add it as a cookie and if the cookie exists then don't do the post back again.

最好的办法是让客户端通过 javascript 向您发送响应。使用标题中包含的屏幕大小变量立即回发到同一页面,将其添加为 cookie,如果 cookie 存在,则不要再次回发。

So step 1: Check if cookie exists with value telling you the client's screen size. (or use session variables) if Yes, run with it. if no, have a javascript that sends you to the same page with a query string identifying the window size. Step 2: if no cookie exists and you have the query string indicating the window size, create the cookie and format accordingly.

所以第 1 步:检查 cookie 是否存在,其值告诉您客户端的屏幕大小。(或使用会话变量)如果是,则使用它运行。如果不是,请使用 javascript 将您发送到同一页面,并带有标识窗口大小的查询字符串。第 2 步:如果不存在 cookie 并且您有指示窗口大小的查询字符串,则创建相应的 cookie 和格式。

回答by CodeOwl

You could try

你可以试试

$userBrowserAtts = get_browser(null, true)

Returns a handy array of all sorts of information about the browser. But beware- this relies on the $_SERVER['HTTP_USER_AGENT'] and this can be spoofed. So this method isn't bullet proof. I don't know if it returns screen-width as such, but you should probably be able to find out if it's mobile, or if it's a tablet or desktop.

返回有关浏览器的各种信息的方便数组。但要注意——这依赖于 $_SERVER['HTTP_USER_AGENT'] 并​​且可以被欺骗。所以这个方法不是防弹的。我不知道它是否会返回屏幕宽度,但您应该能够确定它是移动设备,还是平板电脑或台式机。

handy:

便利:

http://www.php.net/manual/en/function.get-browser.php

http://www.php.net/manual/en/function.get-browser.php

The best way to do this kind of thing is with the CSS3 media queries, but if the server really has to know about the browser, this is about the only thing you can do.

做这种事情的最好方法是使用 CSS3 媒体查询,但如果服务器真的必须知道浏览器,这是你唯一能做的事情。