Making text in a linked div selectable

跟風遠走 提交于 2019-12-13 14:26:48

问题


I am creating a web page and have a section that I want to be linked, inside this section though I have some text that I want to allow the user to copy and paste from (i.e they need to be able to highlight it). Because the text is inside the linked div though I am unable to select it, how can I make the text selectable?

Here is the code I have...

<a href="http://google.com">
    <div class="container"> 
        <h2>Heading</h2>
        <p class="selectable-text">Text that can be highlighted here</p>
        <p>Other Text</p>
    </div>
</a>

I've tried putting this in the CSS, but this just changed the cursor, it didn't actually make the text selectable...

.selectable-text{
    cursor:text;
}

Thanks in advance for any help.


回答1:


a-Elements don't allow block-elements inside of them. So you cannot structure your layout that way. What about only making the heading a link? That would be fine and you could easily select the other text:

<div class="container"> 
    <h2><a href="http://example.com">Heading</a></h2>
    <p>Text that can be highlighted here</p>
    <p>Other Text</p>
</div>

In order to make the whole container clickable, you can apply a Javascript Event Listener to all containers. If you are already using jQuery, this can be done very easily:

$('.container').each(function(){
    $(this).on('click', function(){
        location.href = $(this).find('a').attr('href');
    });
}).addClass('link');

The difference from this to a "real" link is that it won't be draggable and instead selectable. Anyway you can click on it and it will locate you to where you want to go. It will also apply a class .link which you can use in your stylesheet in order to set a pointer as the cursor.

For people who have javascript disabled there will still be a link in the heading, so your page stays usable in every case.



来源:https://stackoverflow.com/questions/10414071/making-text-in-a-linked-div-selectable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!