简体   繁体   中英

Make only part of a div visible

I want a div that only partly has its content visible. I want the user to use his mouse horizontally (ie, left-to-right mouse movement) to change which part of the div is visible.

How can I do this?

The HTML and CSS

If I understand your question correctly, you have a div that is x pixels wide, and its contents are y pixels wide where x > y . In other words, the div 's contents are wider than the div itself.

The following HTML and CSS are an example of how to hide part of the div if x = 250 and y = 500:

​<div id="outer-div" style="width:250px;overflow:hidden;">
<div style="width:500px;">
....
</div>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

The CSS overflow:hidden hides the horizontal scrollbar. If you would like the user to see the horizontal scrollbar, use overflow:auto . If the horizontal scrollbar is all you require, then there is no need to write any JavaScript.


The JavaScript

Changing which part of the div is visible based on mouse movement requires JavaScript. One way to accomplish this is to change the scroll position of the outer-div . has the method Element.scrollTo . Other JavaScript frameworks have something similar.

$('outer-div').addEvent('mousemove', function(event) {
    $('outer-div').scrollTo(event.client.x);
});

See this fiddle for an example.

Use the CSS overflow property:

#element {
    overflow: hidden;
    width: 200px;
}

You can then scroll the div left or right using the scrollLeft property:

document.getElementById("element").scrollLeft = 100;

jsFiddle: http://jsfiddle.net/vHEPv/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM