【问题标题】:FadeIN FadeOUT page transition javascript bugFadeIN FadeOUT 页​​面转换 javascript bug
【发布时间】:2018-05-19 01:25:48
【问题描述】:

当我单击任何链接以将我带到一个新的 HTML 页面时,javascript 会将我路由到同一个 HTML 页面,而不是每个链接单独的 href。

这是我的代码

$(document).ready(function() {
  $('body').css('display', 'none');
  $('body').fadeIn(1000);
  $('.link').click(function(event) {
    event.preventDefault();
    newLocation = $('.link a').attr("href");
    $('body').fadeOut(1000, newpage);
  });
  function newpage() {
    window.location = newLocation;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="music" class="link"><a href="pages/music/index.html">Music</a></div>
<div id="exhibition" class="link"><a href="pages/exhibition/index.html">Exhibition</a></div>
<div id="contact" class="link"><a href="pages/contact/index.html">Contact</a></div>
<div id="about" class="link"><a href="pages/about/index.html">About</a></div>

我的目标是加载页面 FadeIN 并在单击链接时淡出,我得到了我想要的效果,但我不确定链接的这个问题是什么 - 有人知道吗?

【问题讨论】:

  • 你能粘贴你的html代码吗
  • 我已经添加了
  • 我觉得部分问题可能是您阻止了点击 div 的默认设置,而不是实际点击的 &lt;a&gt;。我还没有测试过这个。另外作为旁注,newLocation = $('.link a').attr("href"); 正在对链接执行全局查找,而不是仅使用刚刚单击的 div 进行上下文查找。
  • 它在我们的系统中运行良好,是什么问题?
  • 它仍然发生在我身上,你认为这可能是某种缓存问题吗?

标签: javascript jquery html


【解决方案1】:

正如@Taplar 所说,当您从链接的href 获取位置时,您没有找到正确的位置。您只需获取文档中的第一个链接并查看其href 属性。

您可以通过替换它来轻松解决此问题(它会查找文档中所有具有link 类祖先的锚元素,然后返回它找到的第一个):

newLocation = $('.link a').attr('href');

使用这个(它找到所有锚元素作为任何元素的子元素,该元素注册了被点击的点击处理程序):

newLocation = $(event.currentTarget).find('a').attr('href');

您正在做的另一件事很棘手,但不一定会破坏任何东西,它依赖于newLocationclick 处理程序和newpage 函数之间正确共享。相反,我建议您将参数显式传递给 newpage,以便它更具可重用性,并且您可以确定值的来源。

你可以在下面看到这个工作。

$(document).ready(function() {
  $('body').css('display', 'none');
  $('body').fadeIn(1000);
  $('.link').click(function(event) {
    event.preventDefault();
    newLocation = $(event.currentTarget).find('a').attr('href');
    // Pass anonymous function to fadeOut that calls newpage with newLocation
    $('body').fadeOut(1000, function () { newpage(newLocation); });
  });
  // newpage now accepts a parameter and uses it
  function newpage(location) {
    // Print to console so you can see what URL is getting used
    // You'll always get 404 using StackOverflow's UI since they don't have the relevant pages
    console.log(location);
    window.location = location;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="music" class="link"><a href="pages/music/index.html">Music</a></div>
<div id="exhibition" class="link"><a href="pages/exhibition/index.html">Exhibition</a></div>
<div id="contact" class="link"><a href="pages/contact/index.html">Contact</a></div>
<div id="about" class="link"><a href="pages/about/index.html">About</a></div>

【讨论】:

  • 太棒了!如果您对它感到满意,请“接受”答案:)
猜你喜欢
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多