当只显示一个特定的锚链接(myurl.com/#about)时,我想有条件地显示一个div。我在css中将.dynamic-content设置为display: none。#default-content show,所以我知道我已经接近了,但我对这个级别的脚本还是个新手。让它工作的最好方法是什么?谢谢!
(function($) {
// Parse the URL parameter
function getParameterByName(name, url) {
if (!url) {
url = location.href.split("#").slice(-1)[0];
}
return url;
}
// Give the parameter a variable name
var dynamicContent = getParameterByName('#');
$(document).ready(function() {
// Check if the URL parameter is about
if (dynamicContent == 'about') {
$('#about').show();
}
// Check if the URL parameter is expertise
else if (dynamicContent == 'expertise') {
$('#expertise').show();
}
// Check if the URL parameter is contact
else if (dynamicContent == 'contact') {
$('#contact').show();
}
// Check if the URL parmeter is empty or not defined, display default content
else {
$('#default-content').show();
}
});
})(jQuery); <div id="default-content" class="dynamic-content">
This is the default content
</div>
<!-- Dynamic Section 1 -->
<div id="contact" class="dynamic-content">
Contact content
</div>
<!-- Dynamic Section 2 -->
<div id="expertise" class="dynamic-content">
Expertise content
</div>
<!-- Dynamic Section 3 -->
<div id="about" class="dynamic-content">
About content
</div>
发布于 2019-03-07 06:47:13
您当然可以使用Taplar推荐的方法,也可以废弃它,只将css与:target伪选择器See css tricks here一起使用。
本质上,您将像已经做的那样隐藏部分,然后使用display:block添加一个类,如下所示
#contact:target {
display: block;
}诚然,显示默认内容有点棘手。您可以测试散列中是否存在某个值,如果不存在,则显示默认内容。
编辑:使用伪选择器查看this question的接受答案
Here's a link to that question
你也许可以做一些类似这样的事情:
/* based onhttps://stackoverflow.com/questions/6867095/css-selector-when-target-empty */
.section-wrapper>.dynamic-content:target~#default-content,
.section-wrapper>.dynamic-content {
display: none;
}
.dynamic-content>#default-content,
.dynamic-content>.dynamic-content:target {
display: block;
}<div class="section-wrapper">
<div id="default-content" class="dynamic-content">
This is the default content
</div>
<!-- Dynamic Section 1 -->
<div id="contact" class="dynamic-content">
Contact content
</div>
<!-- Dynamic Section 2 -->
<div id="expertise" class="dynamic-content">
Expertise content
</div>
<!-- Dynamic Section 3 -->
<div id="about" class="dynamic-content">
About content
</div>
<!-- Dynamic Section 3 -->
</div>
时间用完了,所以没有机会测试,但是像这样的东西应该可以工作
发布于 2019-03-07 06:48:24
你可以简化你的逻辑。您可以将有效散列映射到选择器,以显示它们。查找选择器,如果未找到,则使用默认值,并显示该部分。
$(document).ready(function() {
var contentByHash = {
about: '#about'
, expertise: '#expertise'
, contact: '#contact'
};
var hash = window.location.hash.slice(1);
$(contentByHash[hash] || '#default-content').show();
});https://stackoverflow.com/questions/55033328
复制相似问题