jQuery를 사용하여 텍스트 선택을 비활성화하는 방법은 무엇입니까?
jQuery 또는 jQuery-UI에는 주어진 문서 요소에 대한 텍스트 선택을 비활성화하는 기능이 있습니까?
jQuery 1.8에서는 다음과 같이 수행할 수 있습니다.
(function($){
$.fn.disableSelection = function() {
return this
.attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
};
})(jQuery);
jQuery UI를 사용하는 경우 이를 위한 방법이 있지만 마우스 선택만 처리할 수 있습니다(+A는 여전히 작동 중).
$('.your-element').disableSelection(); // deprecated in jQuery UI 1.9
jQuery UI를 사용하지 않으려면 코드가 매우 간단합니다.
$(el).attr('unselectable','on')
.css({'-moz-user-select':'-moz-none',
'-moz-user-select':'none',
'-o-user-select':'none',
'-khtml-user-select':'none', /* you could also put this in a class */
'-webkit-user-select':'none',/* and add the CSS class here instead */
'-ms-user-select':'none',
'user-select':'none'
}).bind('selectstart', function(){ return false; });
저는 이 답변(텍스트 테이블의 강조 표시 방지)이 가장 유용하며, 아마도 IE 호환성을 제공하는 다른 방법과 결합될 수 있을 것입니다.
#yourTable
{
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
}
다음은 연결 끊기 선택 및 일부 단축키(a예:c + 및 +) 취소에 대한 보다 포괄적인 솔루션입니다.검정:a + 및 +)c
(function($){
$.fn.ctrlCmd = function(key) {
var allowDefault = true;
if (!$.isArray(key)) {
key = [key];
}
return this.keydown(function(e) {
for (var i = 0, l = key.length; i < l; i++) {
if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
allowDefault = false;
}
};
return allowDefault;
});
};
$.fn.disableSelection = function() {
this.ctrlCmd(['a', 'c']);
return this.attr('unselectable', 'on')
.css({'-moz-user-select':'-moz-none',
'-moz-user-select':'none',
'-o-user-select':'none',
'-khtml-user-select':'none',
'-webkit-user-select':'none',
'-ms-user-select':'none',
'user-select':'none'})
.bind('selectstart', false);
};
})(jQuery);
및 호출 예:
$(':not(input,select,textarea)').disableSelection();
이것은 또한 이전 버전의 FireFox에 충분하지 않을 수 있습니다(어느 것인지 알 수 없습니다).이 모든 것이 작동하지 않으면 다음을 추가합니다.
.on('mousedown', false)
다음은 모든 공통 브라우저(IE, Chrome, Mozilla, Opera 및 Safari)에서 모든 클래스 '항목'을 선택할 수 없도록 합니다.
$(".item")
.attr('unselectable', 'on')
.css({
'user-select': 'none',
'MozUserSelect': 'none'
})
.on('selectstart', false)
.on('mousedown', false);
$(document).ready(function(){
$("body").css("-webkit-user-select","none");
$("body").css("-moz-user-select","none");
$("body").css("-ms-user-select","none");
$("body").css("-o-user-select","none");
$("body").css("user-select","none");
});
이 작업은 JavaScript를 사용하여 쉽게 수행할 수 있습니다. 이 작업은 모든 브라우저에 적용됩니다.
<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") //For IE
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
target.style.MozUserSelect="none"
else //All other route (For Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
</script>
이 함수 호출
<script type="text/javascript">
disableSelection(document.body)
</script>
이것은 사실 매우 간단합니다.텍스트 선택을 비활성화하고 텍스트를 +끌기(예: Chrome의 링크)를 클릭하려면 다음 jQuery 코드를 사용합니다.
$('body, html').mousedown(function(event) {
event.preventDefault();
});
이 모든 것은 마우스로 클릭할 때 기본값이 발생하는 것을 방지하는 것입니다.mousedown()) 에서body그리고.html태그. 두 따옴표 사이의 텍스트를 변경하는 것만으로 요소를 매우 쉽게 변경할 수 있습니다(예: 변경).$('body, html')로.$('#myUnselectableDiv')을 만들기 위해myUnselectableDivdiv는, 음, 선택할 수 없습니다.
이를 보여주고 증명할 수 있는 간단한 정보:
$('#no-select').mousedown(function(event) {
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="no-select">I bet you can't select this text, or drag <a href="#">this link</a>, </span>
<br/><span>but that you can select this text, and drag <a href="#">this link</a>!</span>
이 효과는 완벽하지 않으며 전체 창을 선택할 수 없도록 하면서 최상의 성능을 발휘합니다.추가할 수도 있습니다.
바로 가기 키(예: 및 )의 일부 취소테스트: 및 )
또한, 위의 블라디미르의 답변 섹션을 사용함으로써.(여기서 그의 게시물로 이동)
저는 모든 접근법을 시도해 보았는데, 제가 IWebBrowser2를 사용하고 있고 10개의 브라우저를 가지고 있지 않기 때문에 이 방법이 가장 간단합니다.
document.onselectstart = new Function('return false;');
저한테 딱 맞습니다!
크롬용 1라인 솔루션:
body.style.webkitUserSelect = "none";
및 FF:
body.style.MozUserSelect = "none";
IE는 "선택할 수 없는" 특성(아래 세부 정보)을 설정해야 합니다.
저는 이것을 크롬에서 테스트했고 작동합니다.이 속성은 상속되므로 본문 요소에 설정하면 전체 문서에서 선택할 수 없습니다.
자세한 내용은 http://help.dottoro.com/ljrlukea.php 를 참조하십시오.
Closure(닫기)를 사용하는 경우 다음 기능을 호출합니다.
goog.style.setUnselectable(myElement, true);
모든 브라우저를 투명하게 처리합니다.
IE 이외의 브라우저는 다음과 같이 처리됩니다.
goog.style.unselectableStyle_ =
goog.userAgent.GECKO ? 'MozUserSelect' :
goog.userAgent.WEBKIT ? 'WebkitUserSelect' :
null;
여기서 정의: http://closure-library.googlecode.com/svn/!svn/bc/4/trunk/closure/goog/docs/closure_goog_style_style.js.source.html
IE 부분은 다음과 같이 처리됩니다.
if (goog.userAgent.IE || goog.userAgent.OPERA) {
// Toggle the 'unselectable' attribute on the element and its descendants.
var value = unselectable ? 'on' : '';
el.setAttribute('unselectable', value);
if (descendants) {
for (var i = 0, descendant; descendant = descendants[i]; i++) {
descendant.setAttribute('unselectable', value);
}
}
나는 이 코드가 모든 브라우저에서 작동하고 최소한의 오버헤드를 필요로 한다고 생각합니다.이것은 위의 모든 대답들의 혼합입니다.벌레가 발견되면 알려주세요!
CSS 추가:
.no_select { user-select: none; -o-user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select:none;}
jQuery 추가:
(function($){
$.fn.disableSelection = function()
{
$(this).addClass('no_select');
if($.browser.msie)
{
$(this).attr('unselectable', 'on').on('selectstart', false);
}
return this;
};
})(jQuery);
선택 사항:모든 하위 요소에 대해서도 선택을 비활성화하려면 IE 블록을 다음으로 변경할 수 있습니다.
$(this).each(function() {
$(this).attr('unselectable','on')
.bind('selectstart',function(){ return false; });
});
용도:
$('.someclasshere').disableSelection();
이에 대한 한 가지 해결책은 적절한 경우에 사용하는 것을 사용하는 것입니다.<button>선택하지 않을 텍스트에 대해 선택합니다.에 이 있는 click일부 텍스트 블록에서 이벤트가 발생하고 해당 텍스트를 선택할 수 없도록 하려면 버튼으로 변경하면 의미가 향상되고 텍스트가 선택되지 않습니다.
<button>Text Here</button>
내가 찾은 최선의 가장 간단한 방법은 ctrl+c, 마우스 오른쪽 버튼 클릭을 방지하는 것입니다.이 경우 제가 모든 것을 차단했기 때문에 지정할 필요가 없습니다.
$(document).bind("contextmenu cut copy",function(e){
e.preventDefault();
//alert('Copying is not allowed');
});
언급URL : https://stackoverflow.com/questions/2700000/how-to-disable-text-selection-using-jquery
'programing' 카테고리의 다른 글
| PHP 사이트에서 xss 공격을 피하기 위한 최상의 방법은 무엇입니까? (0) | 2023.08.13 |
|---|---|
| NumPy 배열의 임플레이스 유형 변환 (0) | 2023.08.13 |
| C에서 %g과 %f의 차이는 무엇입니까? (0) | 2023.08.13 |
| Form control valueChanges는 이전 값을 제공합니다. (0) | 2023.08.13 |
| Android API 21 도구 모음 패딩 (0) | 2023.08.13 |