[英]Addclass when div width is greater than 80%
How to addclass when div width is greater than 80% ?当 div 宽度大于 80% 时如何添加类? This is what I just tried这是我刚刚尝试过的
<div class="wrap_bar">
<div class="bar" style="width:50%;"></div>
</div>
<div class="box"></div>
<script>
var barTotal = $(".bar");
var box= $(".box");
var width = barTotal.width();
if (width > 80%)
box.addClass('type2')
</script>
This code is not working well.这段代码不能正常工作。 Please help请帮忙
If you need this dimension detection only one time (when DOM loaded) then you can just following approach.如果您只需要一次此维度检测(当 DOM 加载时),那么您只需遵循以下方法即可。
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
$(document).ready(function(){
addWhenResized('.bar');
})
But main challenge will be there if you want detect the run time dimension change.但是,如果您想检测运行时维度的变化,那么主要的挑战就是存在。 Then need to take help from here: http://marcj.github.io/css-element-queries/然后需要从这里获得帮助: http : //marcj.github.io/css-element-queries/
After added the plugins from above given link you should follow the following approach:从上面给定的链接添加插件后,您应该遵循以下方法:
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
new ResizeSensor(jQuery('.bar'), function(){
addWhenResized('.bar');
});
Try this:试试这个:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> document.addEventListener("DOMContentLoaded", function(event) { var barTotal = $(".bar"); var barTotalWidth = barTotal.width(); var box= $(".box"); var boxWidth = box.width(); var widthPercent = boxWidth / barTotalWidth; console.log(widthPercent); if (widthPercent > 0.8) box.addClass('type2'); }); </script> <div class="bar" style="width:200px;height:100px;background-color:red"> </div> <div class="box" style="width:190px;height:80px;background-color:blue"> </div>
your codes don't work because you've just called javascript once when the page loaded , you have to wrap it into an event !您的代码不起作用,因为您在页面加载时刚刚调用了一次 javascript,您必须将其包装到一个事件中! Take a look that answer看看那个答案
or that answer或者那个答案
jQuery(document).ready(function($) { jQuery(document).ready(function($) {
if ($(this).width() > 768) {
$('#service-1').addClass('row text-center');
} else {
$('#service-1').removeClass('row text-center');
}
}); });
this will work fantastic when width is less than or more than will add or remove the class当宽度小于或大于添加或删除类时,这将非常有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.