2017-02-21 6 views
3

Я пытаюсь сделать ссылку href на привязку на другой странице (назовем ее страницей 2, чтобы сделать ее проще), однако на странице 2 якорь, о котором идет речь, содержится в div который сначала скрывается, когда вы впервые его посещаете (Div расширяется, чтобы отображать контент при нажатии заголовка. Поэтому, конечно, по умолчанию у div есть свойство «display: none»).Якорь к элементу внутри скрытого div

Вот небольшой образец точного вида вещей, о котором я говорю.

<html> 
 

 
<head> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<style> 
 
p {color:#000;} 
 
</style> 
 

 
<script> 
 
$(document).ready(function(){ 
 
    $("#f-hdr").click(function(){ 
 
     $("#hidden").toggle(1000); 
 
    }); 
 
}); 
 
</script> 
 

 
</head> 
 

 

 

 

 
<body> 
 

 
<a href="#anch">Link to anchor within hidden div</a> 
 

 
<h2><a id="f-hdr" href="javascript:void(0)">Div Header</a></h2> 
 

 
<div id="hidden" style="display:none"> 
 

 
<p id="anch">some text</p> 
 

 
</div> 
 

 
</body> 
 
</html>

Спасибо!

EDIT - скажем, если бы я был на странице 1, я хочу иметь возможность открыть ссылку на конкретный элемент на странице «2» (в данном случае, #anch). Но «#anch» содержится в div (#hidden), который скрывается при первом открытии страницы. Изначально для доступа к содержимому в «#hidden» пользователь должен щелкнуть заголовок, который расширяет div для отображения содержимого. Я хотел бы иметь возможность щелкнуть ссылку на «#anch» (что приведет меня к «странице 2») и просмотреть содержимое в «#anch», не нажимая сначала заголовок.

Из того, что я видел, это может иметь какое-то отношение к событию onhashchange. Хотя я не слишком уверен (отсюда сообщение) :)

+1

Каков ваш вопрос? – bowl0stu

+0

Извинения за недостаток ясности см. В разделе редактирования. –

ответ

0

Есть два способа выполнения этого один, используя имя атрибута якорный как предложено w3schools.

w3schools: https://www.w3schools.com/tags/att_a_name.asp

И другой подход мог бы использовать общий метод JQuery, который ведет себя как имя якоря.

HTML:

<a class="nameLink" href="#hidden" >Link to anchor within hidden div</a> 

<h2><a id="f-hdr" href="javascript:void(0)">Div Header</a></h2> 
<p class="dummy-height"></p> 
<div id="hidden" > 
    <p id="anch">some text</p> 
</div> 

JQuery:

$(document).ready(function(){ 
    $("#f-hdr").click(function(){ 
     $("#hidden").toggle(1000); 
    }); 
    $(".nameLink").on('click', function(){ 
       $($(this).attr('href')).show(); 
    }) 
}); 

Примечание: Здесь nameLink это класс, который может быть присвоен какой-либо ссылки якорь для использования такой же functionlity.

Наконец ссылка:

https://jsfiddle.net/Ashokkumargupta/bc1drx0s/

Надеется, что это решит вашу проблему.

Спасибо, Ashok

+0

Warmer, но, к сожалению, нет (извините! Начав сожалеть о выборе слов в вопросе, ха-ха) Я переработал скрипку в нечто более близкое к тому, над чем я работаю - https://jsfiddle.net/bc1drx0s/5/Я хочу, чтобы иметь возможность щелкнуть ссылку и связать ее с «человеком, которого я ищу». Я понимаю, что это невозможно, в то время как содержащий div имеет свойство «display: none». Мне нужна ссылка, чтобы перейти к «человеку, которого я ищу», без ручного расширения div сначала (если это имеет смысл) - Спасибо за вашу помощь. –

+0

Я обновил код и ссылку. Пожалуйста, проверьте. Надеюсь это поможет! :) Ссылка: https://jsfiddle.net/Ashokkumargupta/bc1drx0s/ –

0

Решение состоит в том, что вам необходимо использовать visibility: hidden вместо display: none.

Я имею в виду что вам нужно изменить:

<div id="hidden" style="display:none"> 
    <p id="anch">some text</p> 
</div> 

К этому:

<div id="hidden" style="visibility: hidden"> 
    <p id="anch">some text</p> 
</div> 

Для получения дополнительной информации вы можете проверить этот вопрос What is the difference between visibility:hidden and display:none?

дисплей: нет средства что тег, о котором идет речь, не будет груша на странице вообще (хотя вы все еще можете взаимодействовать с ней через dom). Между другими тегами не будет выделено пространство.

видимость: скрытый означает, что в отличие от дисплея: нет, метка не видна, но пространство выделяется для него на странице. Тег оказано, его просто не видно на странице.

Я отправляю обновление с длинным текстом добавил к нему, чтобы посмотреть, как она идет к элементу скрытые при нажатии на «Ссылка на якорь в скрытом DIV»:

$(document).ready(function(){ 
 
    $("#f-hdr").click(function(){ 
 
     $("#hidden").toggle(1000); 
 
    }); 
 
});
p {color:#000;}
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
 

 
<a href="#anch">Link to anchor within hidden div</a> 
 

 
<h2><a id="f-hdr" href="javascript:void(0)">Div Header</a></h2> 
 

 
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> 
 
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
 
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p> 
 
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p> 
 
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> 
 
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
 
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p> 
 
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p> 
 
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> 
 
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
 
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p> 
 
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p> 
 
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> 
 
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
 
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p> 
 
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p> 
 
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> 
 
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
 
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p> 
 
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p> 
 

 
<div id="hidden" style="visibility: hidden"> 
 
\t <p id="anch">some text</p> 
 
</div>

Смежные вопросы