开发者

How to convert a CSS and a javascript to a class

I have some problems converting the CSS id to a class and the javascript to match it. I need to use the script multiple times on the site

Here my code: CSS:

#first {
    background-color: #FFF;
    width: auto;
    height: auto;
    overflow: hidden;
    padding: 10px;
} 

JavaScript:

开发者_如何学编程
var divh = document.getElementById('first').offsetHeight;

//keep default height
var divh = $("#first").outerHeight();

document.getElementById("first").style.height = "100px";

//toggle functions
$('div:first').toggle(
  function () {
     $("#first").stop().animate({
        height: divh +'px'
     }, 1000);
  },
  function () {
    $("#first").stop().animate({
      height: '100px'
    }, 1000);
  }
)


If I understand correctly you can just do:

.first {
    background-color: #FFF;
    width: auto;
    height: auto;
    overflow: hidden;
    padding: 10px;
}

And the Javascript would be something like this:

var divh = $('.first').offsetHeight;

//keep default height
var divh = $(".first").outerHeight();

$('.first').style.height = "100px";

//toggle functions
$('div:first').toggle(
  function () {
     $(".first").stop().animate({
        height: divh +'px'
     }, 1000);
  },
  function () {
    $(".first").stop().animate({
      height: '100px'
    }, 1000);
  }
)

Just uses the jQuery selector to select the class instead of the ID.


I think you can use a "class selector" to get all the elements belonging to that class and then apply animation to all of them or one by one by using the each function (see here). Something like:

CSS

.first {
background-color: #FFF;
width: auto;
height: auto;
overflow: hidden;
padding: 10px;
} 

JavaScript:

$('.first').each(function () {
    var divh = $(this).outerHeight();
    ecc. ecc.
})


use .first instant of #first


Mark's answer is almost entirely correct.

Although, he changed $('div:first') to $('div.first') which are not the same thing.

:first is part of jQuery selectors to select only the first matched element (see here).

So, if you want to pick the first div, use $('div:first'). If you want to select all divs with the "first" class, use $('div.first').

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜