Prevent text selection when dragging from outside

2019-07-23 17:45发布

问题:

It has been discussed how to disable text from being selected: How to disable text selection highlighting using CSS?

However, I have yet to find a solution that blocks the user from selecting text when dragging from outside the intended target. I'm looking for a solution that works in IE 7/8.

Any ideas?

回答1:

The IE8- onselectstart event and unselectable attribute solutions have already been discussed.

The CSS solution has been published as well. Here is the gist:

<!-- save this file as unselectable.htc and remember where you put it -->
<public:component lightweight="true">
    <public:attach event="ondocumentready" onevent="unselectable()" />
    <script type="text/javascript">
        function unselectable(){
            element.onselectstart = function(){ return false; };
            element.setAttribute('unselectable', 'on', 0);
        }
    </script>
</public:component>

/* add this rule to the existing CSS file */
.unselectable {
    user-select: none;
    -moz-user-select: none;
    -khtml-user-select: none;
    behavior: url(unselectable.htc); /* change this path as needed */
}