IT story

HTML 페이지에서 텍스트를 선택할 수 없게 만드는 방법이 있습니까?

hot-time 2020. 6. 24. 07:31
반응형

HTML 페이지에서 텍스트를 선택할 수 없게 만드는 방법이 있습니까? [복제]


이 질문에는 이미 답변이 있습니다.

탭 이름과 같은 일부 텍스트 요소가있는 HTML UI를 작성 중입니다. 불행히도 사용자가 탭 이름을 두 번 클릭하는 것이 매우 쉽습니다.이 탭 이름은 많은 브라우저에서 기본적으로 선택됩니다.

JavaScript 트릭 으로이 문제를 해결할 수 있습니다 (해답도보고 싶습니다).하지만 CSS / HTML에 모든 브라우저에서 직접 작동하는 무언가가 실제로 있기를 바랍니다.


대부분의 브라우저에서 CSS를 사용하여이 작업을 수행 할 수 있습니다.

*.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in IE 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}

IE <10 및 Opera unselectable의 경우 선택할 수없는 요소 속성 을 사용해야합니다 . HTML의 속성을 사용하여이를 설정할 수 있습니다.

<div id="foo" unselectable="on" class="unselectable">...</div>

안타깝게도이 속성은 상속되지 않습니다. 즉, 안에있는 모든 요소의 시작 태그에 속성을 넣어야합니다 <div>. 이것이 문제라면, 대신 자바 스크립트를 사용하여 요소의 자손에 대해 재귀 적으로이를 수행 할 수 있습니다.

function makeUnselectable(node) {
    if (node.nodeType == 1) {
        node.setAttribute("unselectable", "on");
    }
    var child = node.firstChild;
    while (child) {
        makeUnselectable(child);
        child = child.nextSibling;
    }
}

makeUnselectable(document.getElementById("foo"));

<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code

***********************************************/


function disableSelection(target){

    if (typeof target.onselectstart!="undefined") //IE route
        target.onselectstart=function(){return false}

    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
        target.style.MozUserSelect="none"

    else //All other route (ie: Opera)
        target.onmousedown=function(){return false}

    target.style.cursor = "default"
}



//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"


</script>

편집하다

코드는 http://www.dynamicdrive.com 에서 온 것 같습니다 .


올바른 CSS 변형은 모두 다음과 같습니다.

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

이 시도:

<div onselectstart="return false">some stuff</div>

간단하지만 효과적입니다 ... 모든 주요 브라우저의 현재 버전에서 작동합니다.


Firefox의 경우 CSS 선언 "-moz-user-select"를 "none"에 적용 할 수 있습니다. 설명서를 확인하고 사용자 선택하십시오 .

It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).

Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.


I'm finding some level of success with the CSS described here http://www.quirksmode.org/css/selection.html:

::selection {
    background-color: transparent;
}

It took care of most of the issues I was having with some ThemeRoller ul elements in an AIR application (WebKit engine). Still getting a small (approx. 15 x 15) patch of nothingness that gets selected, but half the page was being selected before.


Absolutely position divs over the text area with a z-index higher and give these divs a transparent GIF background graphic.

Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to display:box, width and height set as well as the transparent background image.


For an example of why it might be desirable to suppress selection, see SIMILE TImeline, which uses drag-and-drop to explore the timeline, during which accidental vertical mouse movement causes the labels to be highlighted unexpectedly, which looks weird.


For Safari, -khtml-user-select: none, just like Mozilla's -moz-user-select (or, in JavaScript, target.style.KhtmlUserSelect="none";).


"If your content is really interesting, then there is little you can ultimately do to protect it"

That's true, but most copying, in my experience, has nothing to do with "ultimately" or geeks or determined plagiarists or anything like that. It's usually casual copying by clueless people, and even a simple, easily defeated protection (easily defeated by folks like us, that is) works quite well to stop them. They don't know anything about "view source" or caches or anything else... heck, they don't even know what a web browser is or that they're using one.


Here's a Sass mixin (scss) for those interested. Compass/CSS 3 doesn't seem to have a user-select mixin.

// @usage use within a rule
// ex. img {@include user-select(none);}
// @param assumed valid user-select value
@mixin user-select($value)
{
    & {
        -webkit-touch-callout: $value;
        -webkit-user-select: $value;
        -khtml-user-select: $value;
        -moz-user-select: $value;
        -ms-user-select: $value;
        user-select: $value;
    }
}

Though Compass would do it in a more robust way, i.e. only add support for vendors you've chosen.


If it looks bad you can use CSS to change the appearance of selected sections.


Any JavaScript or CSS method is easily circumvented with Firebug (like Flickr's case).

You can use the ::selection pseudo-element in CSS to alter the highlight color.

If the tabs are links and the dotted rectangle in active state is of concern, you can remove that too (consider usability of course).


There are many occasions when turning off selectability enhances the user experience.

For instance allowing the user to copy a block of text on the page without copying the text of any interface elements associated with it (that would become interspersed within the text being copied).


Images can be selected too.

There are limits to using JavaScript to deselect text, as it might happen even in places where you want to select. To ensure a rich and successful career, steer clear of all requirements that need ability to influence or manage the browser beyond the ordinary... unless, of course, they are paying you extremely well.


The following works in Firefox interestingly enough if I remove the write line it doesn't work. Anyone have any insight why the write line is needed.

<script type="text/javascript">
document.write(".");
document.body.style.MozUserSelect='none';
</script>

참고URL : https://stackoverflow.com/questions/69430/is-there-a-way-to-make-text-unselectable-on-an-html-page

반응형