[英]jquery responsive on resize not working
我想檢查(調整大小)窗口寬度,然后加載腳本的特殊部分。 當瀏覽器窗口的寬度<500px時,我想滾動到div的頂部(單擊菜單鏈接時),當瀏覽器窗口的寬度> 500px時,我想滾動到div的垂直中間。菜單鏈接。 它可以以某種方式工作,但速度緩慢且有故障。
首先,我創建“調整大小”功能,然后檢查瀏覽器寬度
(function($){
// on load
$(window).resize(function(){
var current_width = $(window).width(); //check width
$('.go').click(function (e) {
if(current_width > 700){ // when min-width 700px than go to center of DIV
e.preventDefault();
var $box = $('.box').eq($(this).data('rel') - 1);
$('html, body').animate({
scrollTop: $box.offset().top - ($(window).height() - $box.outerHeight(true)) / 2 // scroll to verticall middle of div
}, 200);
}
else if(current_width < 700){ // when max-width 700px than go to top of DIV
e.preventDefault();
var $box = $('.box').eq($(this).data('rel') - 1);
$('html, body').animate({
scrollTop: $box.offset().top + 0 // scroll to top of div
}, 200);
}
});
});
})(jQuery);
當id用“文檔准備好”來進行操作時,一切正常……但是“文檔調整大小”會帶來問題。
更新-以這種方式工作:
$(".go").click(function(){
if ($(window).width() < 800) { // if window smaller than 800px
var $box = $('.box').eq($(this).data('rel') - 1);
$('html, body').animate({
scrollTop: $box.offset().top - 0
}, 200);
}
if ($(window).width() > 800) { // if window bigger than 800px
var $box = $('.box').eq($(this).data('rel') - 1);
$('html, body').animate({
scrollTop: $box.offset().top - ($(window).height() - $box.outerHeight(true)) / 2
}, 200);
}
});
最好像這樣附加事件處理程序:
var resizeTimeout; //the timeout prevents triggering the resize event more than once
$(function () {
$(window).resize(function () {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resize, 500);
});
$('.go').click(function (e) {
});
});
function resize() {
if ($(window).width() > 700) {
} else {
}
}
也許是個壞主意,但是您可以在CSS中嘗試以下操作:
@media screen and (min-width: 480px){
$("body").css({"position":"absolute", "top":"12px", "left":"12px"}); //Set your x and y
}
@media screen and (min-width: 768px){
$("body").css({"position":"absolute", "top":"22px", "left":"22px"}); //Set other stuff
}
不需要JavaScript :)
PS:未經測試!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.