问题
I'm a newbie (no kidding?!) and I can't get this to work. What am I doing wrong here? If the screen width is larger than 480 I don't want this function to do anything, only to fire when screen width is 480 and below.
if ( screen.availWidth < 480 ) {
$(document).ready(function(){
$(".reklam").click(function(){
$('.reklam').attr('src','bilder/480/reklam_on.jpg');
});
});
}
回答1:
Because screen size can change (if a user re-sizes the window), would it be more relevant to have the if statement within the event?
See example:
$(document).ready(function(){
$(".reklam").click(function(){
if ($(window).width() < 480) {
$('.reklam').attr('src','bilder/480/reklam_on.jpg');
}
});
});
回答2:
I would check the screen width
1 directly inside the function as shown below:
$(".reklam").click(function(){
var screenWidth = screen.width;
if (screenWidth <= 480) {
$('.reklam').attr('src','bilder/480/reklam_on.jpg');
} else {
alert('Screen width too high!');
}
});
回答3:
$(document).ready(function(){
$(".reklam").click(function(event){
if ( screen.availWidth < 480 ) {
$('.reklam').attr('src','bilder/480/reklam_on.jpg');
}
else {
event.stopPropagation();
return false;
}
});
});
or something like that.
回答4:
var winWidth = 0;
$(window).resize(function() {
winWidth = $(document).width();
});
in your function write
if(winWidth >480)
{
$(".reklam").click(function(){
$('.reklam').attr('src','bilder/480/reklam_on.jpg');
});
}
or
$(document).ready(function(){
$(".reklam").click(function(){
if ($(window).width() < 480) {
$('.reklam').attr('src','bilder/480/reklam_on.jpg');
}
});
});
来源:https://stackoverflow.com/questions/15499953/disable-jquery-function-when-screen-width-larger-than-480