jquery很新,所以请耐心等待。我有两个功能,一个用于桌面,另一个用于平板电脑断点。它们都检查特定DOM元素的长度,并将宽度作为参数传递。我有另一个功能,目前只调用其中一个功能,但有没有办法以某种方式传递一个或另一个基于他们是在平板电脑或移动断点?你可以在setWidth函数中看到它使用calculateDesktop函数。我可以创建两个不同的函数来执行此操作,但这似乎是多余的。有点像jquery的新手请在必要时包含代码示例。
function calculateDesktop(width) {
var desktop= $('.header-item').length;
return width * ($('.header-section').length - desktop);
}
function calculateTablet(width) {
var tablet = $('.header-item.tablet-none').length;
return width * ($('.header-section').length - tablet);
}
function setWidth() {
$('.expand .main-section').each(function() {
var headerClass = $(this).closest('.header-item')).filter(function(it){
return it.match(/^width-/); });
var width = headerClass ? headerClass[0].split('-')[1] : 75;
$(this).css("width", calculateDesktop(width) + "%");
});
}
SUDO CODE(不起作用,但我希望实现的目标)
if ($(window).width() <= 768) {
setWidth(calculateTablet)
} else {
//desktop goes here
setWidth(calculateDesktop)
}
答案 0 :(得分:1)
您可以像以前一样传递函数引用,然后调用该函数引用以获取宽度
function setWidth(fn) {
$('.expand .main-section').each(function () {
var headerClass = $(this).closest('.header-item').filter(function (it) {
return it.match(/^width-/);
});
var width = headerClass ? headerClass[0].split('-')[1] : 75;
$(this).css("width", fn(width) + "%");
});
}
if ($(window).width() <= 768) {
setWidth(calculateTablet)
} else {
//desktop goes here
setWidth(calculateDesktop)
}