gpt4 book ai didi

javascript - jQuery 问题 : Running a function through each and picking up the element

转载 作者:行者123 更新时间:2023-12-02 17:01:58 26 4
gpt4 key购买 nike

所以我在通过 .each 运行函数时遇到问题,jQuery 似乎没有通过“this”获取有问题的元素。下面的代码:(编辑:我试图将某些内容居中,而不管多个元素的屏幕宽度绝对如何)

$(document).ready(function(){
$('.main-feature h1').each(function() {
centerThis();
});
$('.meta-feature h2').each(function() {
centerThis();
});
});//doc-rdy
function centerThis(){
var trackHeight = $(this).height()/2;
var trackWidth = $(this).width()/2;
var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
$(this).css({
"margin-left": -pxInEmsWidth+'em',
"margin-top": -pxInEmsHeight+'em'
});
$(window).resize(function(){
var trackHeight = $(this).height()/2;
var trackWidth = $(this).width()/2;
var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
$(this).css({
"margin-left": -pxInEmsWidth+'em',
"margin-top": -pxInEmsHeight+'em'
});
});
}//centerThis

最佳答案

您应该将 this 作为参数传递给 centerThis 函数:

$(document).ready(function(){
$('.main-feature h1').each(function() {
centerThis(this);
});
$('.meta-feature h2').each(function() {
centerThis(this);
});
});//doc-rdy
function centerThis(elem){
var trackHeight = $(elem).height()/2;
var trackWidth = $(elem).width()/2;
var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
$(elem).css({
"margin-left": -pxInEmsWidth+'em',
"margin-top": -pxInEmsHeight+'em'
});
$(window).resize(function(){
var trackHeight = $(this).height()/2;
var trackWidth = $(this).width()/2;
var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
$(this).css({
"margin-left": -pxInEmsWidth+'em',
"margin-top": -pxInEmsHeight+'em'
});
});
}//centerThis

关于javascript - jQuery 问题 : Running a function through each and picking up the element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25609218/

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