Javascript Mouse Wheel Zooming for a Web Page

2019-04-10 23:09发布

问题:

Scenario :

  • I'm currently trying to build a poor man's Google Maps using scripts and things to simulate all the functions.
  • I have a massive image that I sliced up into tiles and display in a table on the web page.
  • I found a script that enables a user to click and drag to navigate around the map.

Todo :

  • Now I just need to implement zoom.
  • I found scripts to zoom single images but I want to be able to zoom the entire page out as a single element.
    Since I have 100 images tiled to create the map, it's not practical to do it for each individual slice.

    Is there a way to do this?


    The page I have so far can be found at http://minecraft.firedrakecreative.com,
    and then click on the thumbnail.
    Any help is much appreciated!

回答1:

Take a look at this example, it might help you out.

Basically you're gonna have to bind the scroll event and change the behavior. The example uses CSS3 transformations, if that doesn't work for you because it needs to work on old browsers you might need to change the images sizes. But still some browsers don't render the changed size of an image.

Just to give you a path to go, this is an example of what you can do, considering your page HTML:

window.addEventListener('scroll',function(){
    var scrolled = window.scrollY / ( document.getElementById("Table_01").offsetHeight );
    console.log("window.scrollY: " + window.scrollY);
    console.log("scrolled: " + scrolled );
    var zoomLevels = 1; //change to have a different behavior
    var scale = Math.pow( 3, scrolled * zoomLevels);
    var images = document.getElementById("Table_01").getElementsByTagName("img");
    console.log("scale:" + scale);
    for(i=0;i<images.length;i++){
        images[i].width = Math.round(500/scale); //change 500 to your image size
        images[i].height = Math.round(500/scale); //change 500 to your image size
    }
},true);

You can see this DEMO in action here: http://jsfiddle.net/qG6qm/3/

IMPORTANT: for this code to work you have to change your table tag from:

<table id="Table_01" width="5000" height="5000" boder="0" cellspacing="0" cellpadding="0">

to:

<table id="Table_01" boder="0" cellspacing="0" cellpadding="0">


回答2:

If you can use jQuery:

$('domElement').bind('mousewheel', function (e) {
    if (e.originalEvent.wheelDelta / 120 > 0) {
        alert('Up');
    } else {
        alert('Down');
    }
});