我正在尝试运行一个JQuery脚本,当一个图像加载到它的容器中完全适合它时:
// On load...
$(window).on('load', function(){
// Center images on card
$('.card-container').find('.card-img-s, .card-img-m, .card-img-l').each(function(){
centerImage(this);
});
// Center images on card when window resized
$(window).resize(function(){
$('.card-container').find('.card-img-s, .card-img-m, .card-img-l').each(function(){
centerImage(this);
});
});
});
// Center images on thumbnail
function centerImage(imageContainer){
let image = $(imageContainer).find('img')[0];
// If image height/width > container height/width, set class with max-width
if($(image).height() / $(image).width() > $(imageContainer).height() / $(imageContainer).width()){
$(imageContainer).addClass('img-v');
$(imageContainer).removeClass('img-h');
}
// Otherwise, set class with max-height
else{
$(imageContainer).addClass('img-h');
$(imageContainer).removeClass('img-v');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这可以正常工作。但是在一定的屏幕宽度下,我有一个媒体查询,它将容器的宽度从固定的宽度更改为屏幕的100%,这会更改容器的高/宽比。
问题在于,在媒体查询更新容器宽度之前,JQuery似乎正在运行。它在调整窗口大小时可以正常工作-只有在加载时,脚本似乎使用了错误的(旧)比例。
如何确保我的脚本在我的页面加载全媒体查询和所有内容后运行?
发布于 2018-11-08 10:43:39
您需要确保在加载所有文件(css/脚本)之后执行代码
要实现这一点,请将代码放在
$(function() {
// code here
});
这并不意味着所有的脚本都应该放在上面的函数中。您可以像这样使用此函数:
$(function() {
init()
});
var init = function(){
//your jquery code which needs to run after the files are loaded(media query action is performed) goes here
}
https://stackoverflow.com/questions/53201628
复制相似问题