gpt4 book ai didi

javascript - scrollLeft() 的替代方案

转载 作者:行者123 更新时间:2023-11-28 00:05:22 24 4
gpt4 key购买 nike

你好!

我有一个页面具有水平滚动功能。
我有一个侧边栏和一个内容框

在边栏中我有 5 个链接,比如 LINK1 - LINK5

在内容框中,我有 3500px 的宽度,其中包含 5 个 700px 的 div。
所以页面最初加载在第一个 700px 的 div 中。因此,如果我单击链接 3,它将平滑地滚动到第三个 div 部分。

但是,我想在第二个 div 中加载页面。
我能够使用 scrollLeft() 做到这一点

<script>$("div.content1").scrollLeft(700);</script>



但是横向滚动会乱。第二个 div 将充当第一个 div,这意味着当我单击 LINK1 时,它不会向后滚动。

帮忙吗?

*我认为需要这段代码

<script>
function goto(id, t){
//animate to the div id
$(".contentbox-wrapper").stop().animate({"left": -($(id).position().left)}, 1200);
}
</script>

这是 HTML 代码示例

<div id="sidebar1">
<span class="upper">Foods</span><br />
<a href="#" onClick="goto('#rice', this); return false"><span class="lower">Rice, Noodles & Pasta</span></a><br />
<a href="#" onClick="goto('#snacks', this); return false"><span class="lower">Snacks & Tidbits</span></a><br />
<a href="#" onClick="goto('#canned', this); return false"><span class="lower">Canned & Ready to Eat</span></a><br />
<a href="#" onClick="goto('#breakfast', this); return false"><span class="lower">Breakfast Cereal</span></a><br />
<br />

这是我的内容框的示例

<div class="content1">

<div class="contentbox-wrapper">
<div id="rice" class="contentbox" align="center">
<h2>
Rice, Noodles & Pasta
</h2>

<section id="product">
<ul class="clear">
<li data-id="1">
<div href="#">
<a href="images/products/f1/_DSC4640.jpg" class="zoom"><img src="images/products/f1/_DSC4640.jpg" width="200" height="200" /></a>
<h3>Maggi Curry Flavour</h3>
<p>(5 + 1) x 79 G</p>
<h2>Price:$2.40</h2>
</div>
</li>

最佳答案

我已经根据您的标记创建了一个示例。我希望,这就是您要找的东西。我还对您的 JavaScript 做了一些小改动。请参阅下面的解释。

HTML

<nav>
<a>Item 1</a>
<a>Item 2</a>
</nav>

<div class="contentbox-wrapper">
<div>
<h2>Item 1</h2>
</div>
<div>
<h2>Item 2</h2>
</div>
</div>

如果您可以应用这样的标记,其中每个链接的索引对应于每个内容容器的索引,那么您就可以摆脱 JavaScript 部分所需的所有 ID。

CSS

div.contentbox-wrapper {
position: relative;
width: 400px;
height: 200px;
overflow: hidden;
overflow-x: scroll;
font-size: 0;
line-height: 0;
white-space: nowrap;
}

div.contentbox-wrapper > div {
display: inline-block;
width: 400px;
height: 200px;
text-align: center;
}

div.contentbox-wrapper > div:last-child {
margin-right: 0;
}

JavaScript

var container = $('div.contentbox-wrapper');
var boxes = container.children();

$('nav > a').click(function() {
container.stop().animate({
scrollLeft: boxes.eq($(this).index()).get(0).offsetLeft
}, 350);
});

尝试将多次使用的选择器存储在变量中。优点是,您不需要再次重新查询它们。此 JavaScript 不执行任何其他操作,然后使用 .index().eq() 获取与单击的链接对应的框的偏移量。然后在 .animate() 函数中使用这个值来滚动到这个位置。

演示

Try before buy

一些注意事项

  • 如果您在“Rice, Noodles & Pasta”等普通内容中有一个 & 号,您必须像这样转义它:&
  • 不要使用 align="center"。是deprecated since HTML4 .为此目的使用 CSS。

关于javascript - scrollLeft() 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com