입력 초점에서 텍스트 선택
텍스트 입력이 있습니다. 입력이 포커스를 받으면 입력 내부의 텍스트를 선택하고 싶습니다.
jQuery를 사용하면 다음과 같이 할 수 있습니다.
<input type="text" value="test" />
$("input[type=text]").click(function() {
$(this).select();
// would select "test" in this example
});
나는 Angular 방식을 찾으려고 노력했지만 내가 찾은 대부분의 예제는 변경에 대한 모달 속성을보고있는 지시문을 다루고 있습니다. 포커스를받는 입력을 감시하는 지시문이 필요하다고 가정합니다. 어떻게해야합니까?
Angular에서이를 수행하는 방법은 자동 선택을 수행하는 사용자 지정 지시문을 만드는 것입니다.
module.directive('selectOnClick', ['$window', function ($window) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function () {
if (!$window.getSelection().toString()) {
// Required for mobile Safari
this.setSelectionRange(0, this.value.length)
}
});
}
};
}]);
다음과 같이 지시문을 적용하십시오.
<input type="text" value="test" select-on-click />
Update1 : jQuery 의존성을 제거했습니다.
Update2 : 속성으로 제한합니다.
Update3 : 모바일 Safari에서 작동합니다. 텍스트의 일부를 선택할 수 있습니다 (IE> 8 필요).
다음은 사용자가 클릭하여 커서를 입력 상자에 놓을 때 텍스트를 다시 선택하지 않도록하는 향상된 지시문입니다.
module.directive('selectOnClick', function () {
return {
restrict: 'A',
link: function (scope, element) {
var focusedElement;
element.on('click', function () {
if (focusedElement != this) {
this.select();
focusedElement = this;
}
});
element.on('blur', function () {
focusedElement = null;
});
}
};
})
이것은 Angular 1.x에 대한 오래된 대답입니다.
더 좋은 방법은 ng-click
내장 지시문 을 사용하는 것입니다 .
<input type="text" ng-model="content" ng-click="$event.target.select()" />
편집하다:
로 JoshMB는 친절하게 생각 나게했다; Angular 1.2 이상에서 DOM 노드를 참조하는 것은 더 이상 허용되지 않습니다. 그래서 $event.target.select()
컨트롤러 로 옮겼 습니다.
<input type="text" ng-model="content" ng-click="onTextClick($event)" />
그런 다음 컨트롤러에서 :
$scope.onTextClick = function ($event) {
$event.target.select();
};
여기에 바이올린 예제가 있습니다.
제안 된 솔루션 중 어느 것도 나를 위해 잘 작동하지 않았습니다. 빠른 연구 후 나는 이것을 생각해 냈습니다.
module.directive('selectOnFocus', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var focusedElement = null;
element.on('focus', function () {
var self = this;
if (focusedElement != self) {
focusedElement = self;
$timeout(function () {
self.select();
}, 10);
}
});
element.on('blur', function () {
focusedElement = null;
});
}
}
});
제안 된 여러 솔루션이 혼합되어 있지만 클릭 및 초점 (자동 초점 생각) 모두에서 작동하며 입력에서 부분 값을 수동으로 선택할 수 있습니다.
For me, ng-click didn't have sense, because you could never reposition the cursor without selecting all text again, I found this was annoing. Then it is better to use ng-focus, because the text is selected only if the input was not focused, if you click again to reposition the cursor then the text just deselects, as expected, and you can write in between.
I found this approach to be the expected UX behaviour.
Use ng-focus
Option 1: separate code
<input type="text" ng-model="content" ng-focus="onTextFocus($event)" />
and in controller
$scope.onTextFocus = function ($event) {
$event.target.select();
};
Option 2: as an alternative you can join the code above into this "one-liner" (I didn't test this but it should work)
<input type="text" ng-model="content" ng-focus="$event.target.select()" />
The accepted answer is using the click event however if you use the focus event, only the 1st click will fire the event and it also fires when some other method is used to focus on the input (like hitting tab or calling focus in code).
This also makes it unnecessary to check if the element is already focused as Tamlyn's answer suggests.
app.directive('selectOnClick', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('focus', function () {
this.select();
});
}
};
});
In angular 2, this worked for me, both in Chrome & Firefox:
<input type="text" (mouseup)="$event.target.select()">
No directives needed, just add onfocus="this.select()"
native javascript to the input element or text area.
Modified version that worked for me. First click selects text, second click on same element deselects text
module.directive('selectOnClick', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var prevClickElem = null; //Last clicked element
var ignorePrevNullOnBlur = false; //Ignoring the prevClickElem = null in Blur massege function
element.on('click', function () {
var self = this;
if (prevClickElem != self) { //First click on new element
prevClickElem = self;
$timeout(function () { //Timer
if(self.type == "number")
self.select();
else
self.setSelectionRange(0, self.value.length)
}, 10);
}
else { //Second click on same element
if (self.type == "number") {
ignorePrevNullOnBlur = true;
self.blur();
}
else
self.setSelectionRange(self.value.length, self.value.length); //deselect and set cursor on last pos
}
});
element.on('blur', function () {
if (ignorePrevNullOnBlur == true)
ignorePrevNullOnBlur = false; //blur called from code handeling the second click
else
prevClickElem = null; //We are leaving input box
});
}
}
})
참고URL : https://stackoverflow.com/questions/14995884/select-text-on-input-focus
'Programming' 카테고리의 다른 글
vim에서 창을 뒤집는 방법? (0) | 2020.07.16 |
---|---|
Objective-C : 카테고리의 특성 / 인스턴스 변수 (0) | 2020.07.16 |
컨트롤러에서 각도 변환에 대한 올바른 사용 (0) | 2020.07.16 |
한 필드에서 두 필드로 값 나누기 (0) | 2020.07.16 |
디렉토리의 모든 파일 이름을 $ filename_h에서 $ filename_half로 바꾸시겠습니까? (0) | 2020.07.16 |