开发者

jQuery Toggle div class on load depending on the content height

开发者 https://www.devze.com 2023-03-21 21:58 出处:网络
I have a dynamic content loaded on my template. The default div background-color is yellow, but when teh content is longer than 300px div toggles or appends the class that wil change the background-co

I have a dynamic content loaded on my template. The default div background-color is yellow, but when teh content is longer than 300px div toggles or appends the class that wil change the background-color to red. Below is the code.

<!DOCTYPE html>
<head>
<title>Untitled Document</title>
<style type="text/css" media="all">
.short {background-color:yellow;padding:30px; width:200px;}
.long {backgro开发者_StackOverflowund-color:red;padding:30px;width:200px;}
</style>
</head>

<body>
<div class="short">div content</div>
</body>
</html>


Try this

$(document).ready(function(){
  $(".short").each(function(){
    if($(this).height() > 300){
      $(this).removeClass("short").addClass("long");
    }
  });

});


If you changed your html to look something like this:

<div id="messageDiv" class="short">div content</div>

Then you could use some code like this:

$(document).ready(function () {
   var $messageDiv = $("#messageDiv");
   if($messageDiv.height() > 300) {
     $messageDiv.toggleClass("long short");
   }
});

But thats only a rough idea because it not clear how you are dynamically loading content and how we can know when to test the height.


$('div.short, div.long').each(function(){
  if($(this).height() > 300) {
    $(this).removeClass('short').addClass('long');
  } else {
    $(this).removeClass('long').addClass('short');
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号