So I am having an issue running a function via .each, It jQuery doesn't seem to be picking up the element in question via 'this'. Code below: ( Edit: I am attempting to centre something regardless of screen width absolutely for multiple elements)
$(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
You should pass this
as an argument to the centerThis
function:
$(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
您必须将其作为参数提供给要调用的函数centerThis(),并将函数中的$(this)替换为输入参数的名称。
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.