dynamic dropdown menu switching direction
I have a dynamic dropdown menu using jQuery where the number of main navigation links are dependent on a CMS. Is there way to make it so if the dropdown container touches the wrapper of the website then it flips sides and is right aligned so there is no overflow outside of the main webpage container? See http://online.wsj.com/home-page as an example.
EDIT
Here is th code.
<script>
$("ul#navBar li span").click(function() { //When trigger is clicked...
//caching selectors
var $this = $(this),
$parent = $this.parent(),
$siblings = $parent.siblings(),
$dropdowns_siblings = $siblings.find('.dropdown');
$this.next().toggle(); //toggles the dropdown on click
//hide other menus if visible
$dropdowns_siblings.hide();
function rowWidth(){
//Calculate width of ul
var rowWidth = 0;
$parent.find("ul").each(function() {rowWidth += $(this).width(); });
//Set width of .dropdown
$parent.find(".dropdown").css({'width' : rowWidth});
};
return rowWidth();
</script>
<div id="container">
<ul id="navBar">
<li><a href="/">Link 1</a> <span></span>
<div class="dropdown">
开发者_Python百科 dynamic # of cols
</div>
</li>
<li><a href="/">Link 1</a> <span></span>
<div class="dropdown">
dynamic # of cols
</div>
</li>
<li><a href="/">Link 1</a> <span></span>
<div class="dropdown">
dynamic # of cols
</div>
</li>
<li><a href="/">Link 1</a> <span></span>
<div class="dropdown">
dynamic # of cols
</div>
</li>
</ul>
</div>
You can use jQuery.fn.offset and compare to see if jQuery(window).width()
is more than the sum of the left
component of that offset and the width of your menu, and if it's not and the menu is cropped, then update the positioning of the menu to align itself with the other edge of the button (or menu trigger), etc. You'd bind this function to fire when the window gets resized or if there is horizontal scrolling. Sorry if this is too high-level and not enough example code, but it should be enough to get you started.
...
I've solved your problem with an example on JSFiddle. I think it's what you're looking for. I've filled in a lot of missing CSS from your original code, with some non-IE CSS selectors to save time. I also rewrote most of the js. There is definitely room for refinement, but it works well. I also didn't bind it to adjust live when the window is resizing, but I think that's more of an edge case compared to the click bindings.
精彩评论