我创建了这个脚本并且它可以工作,但是我知道它重复得非常糟糕,需要干掉。我理解如何使用变量选择器,但不知道如何不重复这些功能。有人可以帮忙吗?
// JS to add a "More" link to priority announcements when the height is too tall.
$(document).ready(function(){
// If JS is turned on add a height restriction to the announcement
$(".importantNotice .content").addClass("maxHeight");
// If the height is over 245 a "More" link apears
if ($('.importantNotice .content').height() >= 245 || $('.importantNotice .content .landing-no-display').length) {
$('.importantNotice .more').addClass("show");
}
// If the window gets resized it rechecks height
$(window).resize(function(){
if ($('.importantNotice .content').height() >= 245 || $('.importantNotice .content .landing-no-display').length) {
$('.importantNotice .more').addClass("show");
}
if ($('.importantNotice .content').height() < 245 ($.contains('.importantNotice .content').not(':has(.landing-no-display)')) {
$('.importantNotice .more').removeClass("show");
}
});
});
答案 0 :(得分:0)
我会这样做以特别在使用resize
事件
// JS to add a "More" link to priority announcements when the height is too tall.
$(document).ready(function(){
var importantElem = $(".importantNotice");
var contentElem = importantElem.find('.content');
var moreElem = importantElem.find('.more');
var landingElem = contentElem.find('.landing-no-display');
// If JS is turned on add a height restriction to the announcement
contentElem.addClass("maxHeight");
// If the window gets resized it rechecks height
$(window).resize(function(){
// If the height is over 245 a "More" link apears
if (contentElem.height() >= 245 || landingElem.length) {
moreElem.addClass("show");
}else if (contentElem.height() < 245 || landingElem.length == 1) { //using else-if here to minimize the conditional checking
moreElem.removeClass("show");
}
}).trigger('resize'); //triggering `resize` for first time to aviod duplicate code
});