使用锚点到达页面时触发事件
Fire event when arriving in page with anchor
我的问题有点像this one但又不完全一样
我有一个带有锚点的页面,例如。 page.html#video1
。在此页面中,我有多个带有 id 的部分,e。 #video1
、#video2
。每个部分都包含一篇文章和一个显示视频的按钮。
我希望 #video1
部分的视频在到达 page.html#video1
时自动显示。 Javascript 或 jQuery 可以吗?
<div id="video_container"></div>
<div id="video"></div>
<section id="video1">
<p>
article 1
</p>
<button class="video1">
the button that plays the video1
</button>
</section>
<section id="video2">
<p>
article 2
</p>
<button class="video2">
the button that plays the video2
</button>
</section>
$('.video1').click(function() {
$("#video_container").html('<div id="video"><iframe id="portrait_video" class="video_fonc" src="https://www.youtube.com/embed/0itBZI6PiDc?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer&autoplay=1&enablejsapi=1&modestbranding=1" frameborder="0" allowfullscreen ></iframe></div>').fadeIn(400);
$("#video").fitVids();
});
$('.video2').click(function() {
$("#video_container").html('<div id="video"><iframe id="portrait_video" class="video_fonc" src="https://www.youtube.com/embed/0itBZI6PiDc?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer&autoplay=1&enablejsapi=1&modestbranding=1" frameborder="0" allowfullscreen ></iframe></div>').fadeIn(400);
$("#video").fitVids();
});
这是一个jsFiddle
您可以使用 window.location.hash
从 URL 中获取片段。在您的情况下,此值将与包含按钮的 section
的 id
相匹配,因此您只需单击它即可找到相关的 button
和 trigger()
:
var hash = window.location.hash;
if (hash) {
$('section#' + hash).find('button').trigger('click');
}
我的问题有点像this one但又不完全一样
我有一个带有锚点的页面,例如。 page.html#video1
。在此页面中,我有多个带有 id 的部分,e。 #video1
、#video2
。每个部分都包含一篇文章和一个显示视频的按钮。
我希望 #video1
部分的视频在到达 page.html#video1
时自动显示。 Javascript 或 jQuery 可以吗?
<div id="video_container"></div>
<div id="video"></div>
<section id="video1">
<p>
article 1
</p>
<button class="video1">
the button that plays the video1
</button>
</section>
<section id="video2">
<p>
article 2
</p>
<button class="video2">
the button that plays the video2
</button>
</section>
$('.video1').click(function() {
$("#video_container").html('<div id="video"><iframe id="portrait_video" class="video_fonc" src="https://www.youtube.com/embed/0itBZI6PiDc?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer&autoplay=1&enablejsapi=1&modestbranding=1" frameborder="0" allowfullscreen ></iframe></div>').fadeIn(400);
$("#video").fitVids();
});
$('.video2').click(function() {
$("#video_container").html('<div id="video"><iframe id="portrait_video" class="video_fonc" src="https://www.youtube.com/embed/0itBZI6PiDc?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer&autoplay=1&enablejsapi=1&modestbranding=1" frameborder="0" allowfullscreen ></iframe></div>').fadeIn(400);
$("#video").fitVids();
});
这是一个jsFiddle
您可以使用 window.location.hash
从 URL 中获取片段。在您的情况下,此值将与包含按钮的 section
的 id
相匹配,因此您只需单击它即可找到相关的 button
和 trigger()
:
var hash = window.location.hash;
if (hash) {
$('section#' + hash).find('button').trigger('click');
}