2

我有这个代码,如果点击就会显示内容。问题是这个功能只有在屏幕/设备宽度最大为 500 像素时才可用。我该怎么做呢?

$(function () {
    $('.row1').hide();
    $('#show').toggle(function () {
        $('.row1').slideDown("slow");
        $(this).attr("src", "bilder/cancel.png");
    }, function () {
        $('.row1').slideUp("slow");
        $(this).attr("src", "bilder/add.png");
    });
});

更新:我没有很好地解释我想要完成的事情:/我希望当屏幕宽度高于 500 像素时显示此图像。当宽度小于 500 像素时,我想要一条线,上面写着 click here to show image 并出现图像

4

4 回答 4

5

You need to first get the screen width and then you can use an if statement to then run the code you posted above, if the screen width is above the certain width.

For example.

if($(window).width() > 500){
   $('.row1').hide();
   $('#show').toggle(function(){
      $('.row1').slideDown("slow");
      $(this).attr("src","bilder/cancel.png" );
   },function(){
      $('.row1').slideUp("slow");
      $(this).attr("src", "bilder/add.png" );
   });
};

EDIT

Looking at your comments you want to show an image else hide it. I would probably agree this would be nicer and easier to do with css media queries but please see the below edit which shows a JS solution.

if($(window).width() > 500){
   //show the image
   $('.row1').slideDown("slow");
   //etc...   
}else{
   //hide the image
   $('.row1').slideUp("slow");
   //etc...
}
于 2013-03-18T17:30:43.867 回答
2

Try tracking screen.width and screen.height.

Something like this:

    function doSomething(){
        if (screen.width < 500){
            //Do Something
       }
    }
于 2013-03-18T17:30:23.307 回答
2

You can bind the event when the size of the window is less than 500, or use an if statement in your handler. Note that toggle event method is deprecated, you can use slideToggle method instead.

$(function () {
    var $row = $('.row1').hide();
    $('#show').click(function () {
        if ($(window).width() > 500) return;
        $row.stop().slideToggle("slow");
        $(this).prop("src", function(i, src){
            return src === "bilder/cancel.png" 
                   ? "bilder/add.png" 
                   : "bilder/cancel.png";
        });
    });
});

Or:

$(function () {
    if ($(window).width() > 500) {
       var $row = $('.row1').hide();
       $('#show').click(function () {
           $row.stop().slideToggle("slow");
           $(this).prop("src", function(i, src){
                return src === "bilder/cancel.png" 
                       ? "bilder/add.png" 
                       : "bilder/cancel.png";
           });
       });
    }
});
于 2013-03-18T17:31:22.590 回答
1

您还可以将函数绑定到resize事件。每当调整浏览器窗口大小时,这将调用您的函数。

function myFunction() {
    if($(window).width() > 500)
    {   
        //Code to run when greater than...
    }
    else
    {
        //Code to run when less than...
    }
}

//initialize
myFunction();

//call when the page resizes.
$(window).resize(function() {
    myFunction();
});

您可以在此处查看工作的可视化示例:http: //jsfiddle.net/q6BpH/1/

于 2013-03-18T18:00:41.297 回答