gpt4 book ai didi

javascript - 拓宽职能范围

转载 作者:行者123 更新时间:2023-11-28 19:33:50 24 4
gpt4 key购买 nike

我编写了一些 jQuery 函数来调整图像大小,在页面加载时保持其纵横比,并调整窗口大小。这些功能非常有用,但我是专门为一种场景构建的。现在,出现了另一个类似的场景,我必须执行几乎相同的功能,只是使用 iFrame。为了成为一名更好的编码员,并且不添加额外的代码,我如何简洁有效地在整个网站的 iFrame 以及 $('.com-background > img') 场景?

这是 jQuery:

function imageCalc() {
$imgWidth = $('.com-background > img').width();
$imgHeight = $('.com-background > img').height();
$imgAspectRatio = $imgHeight / $imgWidth;
$('.com-background > img').css('margin-left', '-10px' );

}
function setImageDims() {
$('.com-background > img').css('height', function( calcHeight ) { return $imgAspectRatio * $('#main-content').width(); });
$('.com-background > img').css('width', function( calcWidth ) { return $('#main-content').width() + 20; });
}

function imageResize() {
$('.com-background > img').css('width', function( resizeWidth ) { return $("body").width() });
$('.com-background > img').css('height', function( resizeHeight ) { return $imgAspectRatio * $('.com-background > img').width(); });
}

最佳答案

评论中的@nnnnnn 的意思是:

Update the functions to take the selector as an argument instead of hard-coding it?

转动这个:

function imageCalc() {
$imgWidth = $('.com-background > img').width();
$imgHeight = $('.com-background > img').height();
$imgAspectRatio = $imgHeight / $imgWidth;
$('.com-background > img').css('margin-left', '-10px' );

}

对此:

//where selector is your string query
function imageCalc(selector) {
$imgWidth = $(selector).width();
$imgHeight = $(selector).height();
$imgAspectRatio = $imgHeight / $imgWidth;
$(selector).css('margin-left', '-10px' );

}

上述更改将使您的函数通用,从某种意义上说,只要您通过选择器指定要更改的内容,就可以对其他 DOM 对象执行相同的操作争论。要执行您现在正在执行的相同操作,您必须调用 imageCalc('.com-background > img'); 等。

由此,

Also, unrelated to your question, cache your jQuery objects, don't keep re-selecting the same elements within the same function

他的意思是:

//where selector is your string query
function imageCalc(selector) {
var obj=$(selector);
$imgWidth = obj.width();
$imgHeight = obj.height();
$imgAspectRatio = $imgHeight / $imgWidth;
obj.css('margin-left', '-10px' );

}

它的作用是缓存您的对象,这意味着您只需定位它一次,然后重用同一对象。它会对性能产生影响,因为每次使用 $(selector) 时,您都会重新搜索 DOM 树以查找该元素,这确实需要时间。

关于javascript - 拓宽职能范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26267949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com