简体   繁体   中英

jQuery Toggle div class on load depending on the content height

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 {background-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");
    }
  });

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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