首页 > 解决方案 > 无法使用 offset().top - x 读取 top 的属性

问题描述

我有一个我无法发现的奇怪错误。我发现了一个类似的问题,但它与我的错误不相似。

我有一个简单的 JS 函数,可以在单击 href 链接时为滚动设置动画。它在这个 js 小提琴中工作得很好,但它似乎在这个页面上不起作用(即使它是相同的),我找不到潜在的问题。

https://www.wolfandgrizzly.com/pages/instructions

当您选择一种语言时会发生这种情况。

  var e = window.innerWidth;
  $(document).on("click", 'a[href^="#"]', function(s) {
		console.log($.attr(this, "href"));
	  s.preventDefault(), e >= 770 ? $("html, body").animate({
			scrollTop: $($.attr(this, "href")).offset().top - 48
			
	  }, 500) : $("html, body").animate({
		  scrollTop: $($.attr(this, "href")).offset().top - 100
	  }, 500)
	});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:1000px;"><a href="#clickMe">ClickMe</a></div>
<div id="clickMe">

标签: javascripthtml

解决方案


在那个页面上没有任何 id="German"。当您单击 a[href="#German"] 时,浏览器默认滚动(丑陋,非动画)到 ID =whatever_comes_after_hash 的元素。您的函数通过一个很好的平滑向下滚动覆盖了该行为......但它仍然会照顾一个带有id="whatever_comes_after_hash"in的元素a href="#whatever_comes_after_hash"

因此,您需要的解决方案是将 ID 添加到该页面上的元素,它应该可以正常工作。

var e = window.innerWidth;
  $(document).on("click", 'a[href^="#"]', function(s) {
		console.log($.attr(this, "href"));
	  s.preventDefault(), e >= 770 ? $("html, body").animate({
			scrollTop: $($.attr(this, "href")).offset().top - 48
			
	  }, 500) : $("html, body").animate({
		  scrollTop: $($.attr(this, "href")).offset().top - 100
	  }, 500)
	});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="#id_of_target_element">ClickMe</a>

<div style='height: 1000px; background-color: red;'></div>
<div id="id_of_target_element">target element</div>
<div style='height: 1000px; background-color: blue;'></div>


推荐阅读