计算元素的宽度? [英] Calculating the width of an element?

查看:51
本文介绍了计算元素的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取div的宽度,以便可以在php中将其回显.

I'm trying to get the width of a div so that I can echo it out in php.

任何人都可以给我指点一下如何实现这一目标吗?

Can anyone give me a pointer as how to achieve this?

基本上,我想开发一个响应式" < div> ,它将在php中以响应方式显示父÷ div> 的宽度模板.显然,在不同的窗口大小中,响应模板会更改宽度大小,我只需要找到一种方法来输出此宽度并在php中将其回显即可.jQuery已经在后台运行,所以我可以利用它...

Basically, I'm wanting to develop a 'responsive' <div> which will display the width of the parent <div> in php in a responsive template. Obviously, in different window sizes, the responsive template changes width size and I just need to find a way to output this width and echo it out in php. JQuery is already running in the background, so I could tap into that...

只需要一点方向

推荐答案

您无法执行此操作,因为PHP在服务器上运行,因此用户将通过浏览器(通常是另一台计算机)访问该页面.用户在地址栏中输入网址并按回车后,GET请求将被发送到所请求页面的服务器.服务器将运行服务器端脚本(例如,在PHP中),生成页面的结构,并将该结构发送到客户端(即浏览器).服务器将结构发送到浏览器后,PHP代码已经成功完成,但是该结构尚未显示,因此您的 div 尚不存在,更不用说任何 width 值.

You cannot do that, because PHP runs on the server, users will visit the page from their browser, which is usually a different computer. After a user enters a web address into the address bar and hits enter, a GET request will be sent to the server of the page being requested. The server will run a server-side script (in PHP, for instance), generate the structure of the page and send that structure to the client-side, that is, the browser. When the server has sent the structure to the browser, the PHP code was already successfully finished, but the structure was not displayed yet, therefore your divs do not exist yet at that point, let alone having any width values.

因此,要实现的行为对于PHP而言是不可能的,因此您应该以其他方式来实现.我可以用jquery推荐Javascript吗?例如,如果您的外部 div 具有 id ="a" ,而内部 div 具有 id ="b" ,然后您可以使用Javascript执行以下操作:

So, the behavior you intended to achieve is impossible with PHP, therefore you should do it in a different way. May I recomment Javascript with jquery? For instance, if your outer div has id="a" and the inner div has id="b", then you can do the following in Javascript:

$(function() {
    $("#a").resize(function() {
        $("#b").text($(this).width());
    });
});

在这里,您有一个函数,它将在加载事件时运行,然后将 resize 事件注册到外部的 div 中,该事件将根据外部 div width 更改内部 div 的内部文本.

Here, you have a function which will run at load event and then will register a resize event to the outer div, which will change the inner text of the inner div according to the width of the outer div.

这篇关于计算元素的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆