Any way to do “backend media queries” with JS and

2019-06-11 10:30发布

问题:

The project I am working on consists of a grid showing content. I would like to resize each item on the grid to a fourth of the viewport's size. This would be very easy with Javascript, but there is some backend stuff that needs to be aware of the size of each item:

I am using Timthumb to resize the image of item to its appropiate size, so I would need to detect the viewport's width, and send the appropiate value (the viewport's width / 4) to the php that serves each item, so it tells Timthumb the appropiate size to use.

What would be the best approach to this problem?

回答1:

How about when requesting the page, in $(document).ready, detect the size of viewport using jQuery and pass it in an AJAX request?

$(document).ready(function () {
    var height = $(window).height();
    var width = $(window).width();
    $.ajax({
        type: 'POST',
        url: image.php,
        data: {
            "height": height,
            "width": width
        },
        success: function (data) {
            $("#viewarea").html(data);
        },
    });
});

at PHP side you can just get it and return the data

$_POST['height']
$_POST['width']


回答2:

Surely a simple AJAX/JQuery request to the PHP script which generates the image would work here?

Something like:

var query_string = "x=<viewport-x>&y=<viewport-y>";
$('#viewport').html("Processing...");
$('#viewport').load('resize_image.php',query_string);

That way you just need to take the $_GET['x'] and $_GET['y'] vars in your PHP script and pass them to TimThumb before echoing the correct image path back to the page.