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.
})
使用#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').
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.