简体   繁体   English

将div高度设置为相等的宽度(javascript)

[英]Setting div height to equal width ( javascript )

I'm aware this is a popular question. 我知道这是一个受欢迎的问题。 I've read solutions to this including setting padding-bottom to equal width. 我已经读过解决方案,包括将padding-bottom设置为相等的宽度。 As well as assigning this to the pseudo element so it's easier to insert content. 以及将其分配给伪元素,以便于插入内容。 (Plus other css solutions). (加上其他CSS解决方案)。 css height same as width CSS高度与宽度相同

These do work but it's giving me trouble with some of the content I insert and it's not worth the hassle (since my whole site is construction from these squares). 这些方法确实有效,但是它给我插入的某些内容带来了麻烦,并且不值得麻烦(因为我的整个网站都是由这些正方形构成的)。

I'm a novice when it comes to javascript but would there be an easy solution to enable a divs height to equal width. 我是JavaScript的新手,但是有一个简单的解决方案可以使divs高度等于宽度。 ( Sorry I'm too novice to even show an attempt :/ ) (对不起,我还是个新手,连尝试都没有尝试:/)

I try not to ask too many "write code for me" questions so references or explanations would be equally appreciated. 我尽量不要问太多“为我编写代码”问题,因此同样会赞赏您的参考或解释。

Answer: Thanks Jacob just to add onto your code this now works on resize incase anyone else has this same problem https://jsfiddle.net/pekqh5z1/4/ 答案: 谢谢雅各布只是将其添加到您的代码中,如果其他人也遇到相同的问题,现在可以调整大小了https://jsfiddle.net/pekqh5z1/4/

function updateSize(){
var box = $(".test");
box.css("height", box.width());
}

$( window ).resize(updateSize);
$(document).ready(function(){
updateSize();
})

This is super easy to do. 这是超级容易做到的。

To edit set the style of an element with JS, you set the desired property of the style method. 要使用JS编辑设置元素的样式,请设置style方法的所需属性。

 var test = document.querySelector(".test"); test.style.height = getComputedStyle(test).width; 
 .test { background: red; } 
 <div class="test">Super uber goober</div> 

With the JS, we first select the first appearance of .test , and assign it to a variable( var test = document.querySelector(".test"); ) 使用JS,我们首先选择.test的第一个外观,并将其分配给变量( var test = document.querySelector(".test");

We then get the computed width of the element, and set that as its height( test.style.height = getComputedStyle(test).width; ) 然后,我们获得元素的计算宽度,并将其设置为其高度( test.style.height = getComputedStyle(test).width; )。

For the sake of completeness, here's a jQuery solution as well: 为了完整起见,这也是一个jQuery解决方案:

 var test = $(".test"); test.css("height", test.width()); 
 .test { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="test">Super uber goober</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM