Calculating the width of an element?

若如初见. 提交于 2019-12-08 14:00:06

问题


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?

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...

Just need a bit of direction


回答1:


Your PHP code is going to run server side. You'll only be able to determine width client side (e.g. using javascript) after the DOM is generated. You can do so with plain javascript by doing

document.getElementById("yourDivId").offsetWidth

or using jQuery

$("#yourDivId").width()

If you really need the width accessible in your PHP code, you will then need to send a post request (ajax or full) so that PHP can have the value.




回答2:


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.

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());
    });
});

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.



来源:https://stackoverflow.com/questions/36794404/calculating-the-width-of-an-element

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