jQuery UI 대화 상자가 첫 번째 텍스트 상자에 초점을 설정하지 못하게하십시오.
사용자가 링크를 클릭하면 표시되도록 jQuery UI 모달 대화 상자를 설정했습니다. 해당 대화 상자 div 태그에는 두 개의 텍스트 상자 (간결하게 1 코드 만 표시)가 있으며 포커스에 반응하는 jQuery UI DatePicker 텍스트 상자로 변경되었습니다.
문제는 jQuery UI 대화 상자 ( 'open')가 어떻게 든 첫 번째 텍스트 상자에 포커스를 두도록 트리거 한 다음 날짜 선택 달력이 즉시 열립니다.
그래서 초점이 자동으로 발생하는 것을 방지하는 방법을 찾고 있습니다.
<div><a id="lnkAddReservation" href="#">Add reservation</a></div>
<div id="divNewReservation" style="display:none" title="Add reservation">
<table>
<tr>
<th><asp:Label AssociatedControlID="txtStartDate" runat="server" Text="Start date" /></th>
<td>
<asp:TextBox ID="txtStartDate" runat="server" CssClass="datepicker" />
</td>
</tr>
</table>
<div>
<asp:Button ID="btnAddReservation" runat="server" OnClick="btnAddReservation_Click" Text="Add reservation" />
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
var dlg = $('#divNewReservation');
$('.datepicker').datepicker({ duration: '' });
dlg.dialog({ autoOpen:false, modal: true, width:400 });
$('#lnkAddReservation').click(function() { dlg.dialog('open'); return false; });
dlg.parent().appendTo(jQuery("form:first"));
});
</script>
1.10.0 jQuery를 UI 변경 로그 나열 티켓 4731 고정되어있다.
focusSelector가 구현되지 않은 것처럼 보이지만 대신 다양한 요소에 대한 계단식 검색이 사용되었습니다. 티켓에서 :
[오토 포커스]로 시작한 다음 : 태 블러 블 컨텐츠, 버튼 창, 닫기 버튼, 대화 상자로 자동 초점 확장
따라서 요소를 autofocus
속성으로 표시 하면 초점을 가져야하는 요소입니다.
<input autofocus>
에서 문서 , 초점 로직 (제목 '포커스'에서, 단지 목차에서) 설명 :
대화 상자를 열면 포커스가 다음과 일치하는 첫 번째 항목으로 자동 이동됩니다.
autofocus
속성이 있는 대화 상자의 첫 번째 요소:tabbable
대화 상자 내용 의 첫 번째 요소:tabbable
대화 상자의 버튼 창에 있는 첫 번째 요소- 대화 상자의 닫기 버튼
- 대화 자체
그 위에 숨겨진 범위를 추가하고 ui-helper-hidden-accessible을 사용하여 절대 위치로 숨기십시오. jquery-ui의 대화 상자를 사용하고 있으며 jquery-ui에 있기 때문에 클래스가 있다는 것을 알고 있습니다.
<span class="ui-helper-hidden-accessible"><input type="text"/></span>
jQuery UI> = 1.10.2에서 _focusTabbable
프로토 타입 메소드를 위약 함수로 바꿀 수 있습니다 .
$.ui.dialog.prototype._focusTabbable = $.noop;
이것은 dialog
각 페이지를 수동으로 편집 할 필요없이 페이지의 모든에 영향을 미칩니다 .
원래 함수는 autofocus
속성 / tabbable
element / 를 사용하여 첫 번째 요소에 포커스를 설정 하거나 대화 상자 자체로 넘어갈뿐입니다. 사용은 요소에 초점을 맞추는 것이므로 요소로 대체하는 데 아무런 문제가 없습니다 noop
.
다음 코드에서 jQuery UI 대화 상자 기능을 찾았습니다.
c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();
jQuery 동작을 해결하거나 동작을 변경할 수 있습니다.
tabindex -1은 해결 방법으로 작동합니다.
jQuery UI 1.10.0부터 HTML5 속성 autofocus를 사용하여 집중할 입력 요소를 선택할 수 있습니다 .
대화 상자에서 첫 번째 입력으로 더미 요소를 작성하기 만하면됩니다. 그것은 당신을 위해 초점을 흡수합니다.
<input type="hidden" autofocus="autofocus" />
2013 년 2 월 7 일 Chrome, Firefox 및 Internet Explorer (모든 최신 버전)에서 테스트되었습니다.
http://jqueryui.com/upgrade-guide/1.10/#added-ability-to-specify-which-element-to-focus-on-open
놀면서 이것을 알아 냈습니다.
포커스를 제거하기 위해 이러한 솔루션을 사용하여 ESC처음 대화 상자에 들어갈 때 키 작동이 중지되었습니다 (예 : 대화 상자 닫기).
대화 상자가 열리고 즉시를 누르면 대화 상자가 ESC닫히지 않습니다 (활성화 된 경우). 포커스가 숨겨진 필드 또는 다른 것에 있으며 키 누르기 이벤트가 발생하지 않기 때문입니다.
내가 고 쳤던 방법은 이것을 오픈 이벤트에 추가하여 첫 번째 필드에서 포커스를 제거하는 것이 었습니다.
$('#myDialog').dialog({
open: function(event,ui) {
$(this).parent().focus();
}
});
이 대화 상자에 포커스를 설정하면 표시되지 않으며 ESC키가 작동합니다.
입력의 tabindex를 -1로 설정 한 다음 나중에 필요한 경우 tabindex를 복원하도록 dialog.open을 설정하십시오.
$(function() {
$( "#dialog-message" ).dialog({
modal: true,
width: 500,
autoOpen: false,
resizable: false,
open: function()
{
$( "#datepicker1" ).attr("tabindex","1");
$( "#datepicker2" ).attr("tabindex","2");
}
});
});
내 해결 방법 :
open: function(){
jQuery('input:first').blur();
jQuery('#ui-datepicker-div').hide();
},
대화 상자보다 긴 내용이있었습니다. 대화 상자가 열리면 맨 아래에있는 첫 번째 : tabbable과 대화합니다. 여기 내 수정이 있었다.
$("#myDialog").dialog({
...
open: function(event, ui) { $(this).scrollTop(0); }
});
간단한 해결 방법 :
tabindex = 1로 보이지 않는 요소를 만들면 ... 날짜 선택기가 초점을 맞추지 않습니다 ...
예 :
<a href="" tabindex="1"></a>
...
Here comes the input element
다음은 jQuery UI 티켓 # 4731 을 읽은 후에 구현 한 솔루션입니다 . 원래 slolife가 다른 답변에 대한 응답으로 게시했습니다. (티켓도 그에 의해 만들어졌습니다.)
먼저, 페이지에 자동 완성을 적용하는 데 사용하는 방법에 관계없이 다음 코드 줄을 추가하십시오.
$.ui.dialog.prototype._focusTabbable = function(){};
이는 jQuery의 "자동 초점"동작을 비활성화합니다. 사이트에 계속 액세스 할 수있게하려면 대화 상자 작성 방법을 래핑하여 추가 코드를 추가하고 첫 번째 입력 요소에 초점을 맞추기위한 호출을 추가하십시오.
function openDialog(context) {
// Open your dialog here
// Usability for screen readers. Focus on an element so that screen readers report it.
$("input:first", $(context)).focus();
}
키보드를 통해 자동 완성 옵션을 선택할 때 접근성을 더욱 높이기 위해 jQuery UI의 "select"자동 완성 콜백을 재정의하고 일부 추가 코드를 추가하여 선택 후 IE 8에서 textElement가 포커스를 잃지 않도록합니다.
요소에 자동 완성을 적용하는 데 사용하는 코드는 다음과 같습니다.
$.fn.applyAutocomplete = function () {
// Prevents jQuery dialog from auto-focusing on the first tabbable element.
// Make sure to wrap your dialog opens and focus on the first input element
// for screen readers.
$.ui.dialog.prototype._focusTabbable = function () { };
$(".autocomplete", this)
.each(function (index) {
var textElement = this;
var onSelect = $(this).autocomplete("option", "select");
$(this).autocomplete("option", {
select: function (event, ui) {
// Call the original functionality first
onSelect(event, ui);
// We replace a lot of content via AJAX in our project.
// This ensures proper copying of values if the original element which jQuery UI pointed to
// is replaced.
var $hiddenValueElement = $("#" + $(textElement).attr('data-jqui-acomp-hiddenvalue'));
if ($hiddenValueElement.attr("value") != ui.item.value) {
$hiddenValueElement.attr("value", ui.item.value);
}
// Replace text element value with that indicated by "display" if any
if (ui.item.display)
textElement.value = ui.item.display;
// For usability purposes. When using the keyboard to select from an autocomplete, this returns focus to the textElement.
$(textElement).focus();
if (ui.item.display)
return false;
}
});
})
// Set/clear data flag that can be checked, if necessary, to determine whether list is currently dropped down
.on("autocompleteopen", function (event, ui) {
$(event.target).data().autocompleteIsDroppedDown = true;
})
.on("autocompleteclose", function (event, ui) {
$(event.target).data().autocompleteIsDroppedDown = false;
});
return this;
}
닫기 버튼에 초점을 맞추기 위해이 옵션을 제공 할 수 있습니다.
.dialog({
open: function () {
$(".ui-dialog-titlebar-close").focus();
}
});
이것은 jQuery 플러그인 문제가 아닌 브라우저 동작 일 수 있습니다. 팝업을 연 후 프로그래밍 방식으로 초점을 제거해 보셨습니까?
$('#lnkAddReservation').click(function () {
dlg.dialog('open');
// you may want to change the selector below
$('input,textarea,select').blur();
return false;
});
그것을 테스트하지는 않았지만 정상적으로 작동합니다.
동일한 문제를 해결하고 대화 상자를 열 때마다 포커스를 훔치는 datepicker 앞에 빈 입력을 삽입하여 해결했습니다. 이 입력은 대화 상자를 열 때마다 숨겨져 닫히면 다시 표시됩니다.
글쎄, 아무도 해결책을 찾지 못했다는 것이 멋지다. 나쁜 소식은 내부에 입력과 링크가 없어도 대화 상자가 포커스를 잡는다는 것입니다. 대화 상자를 도구 설명으로 사용하고 원래 요소에 초점을 유지해야합니다. 내 해결책은 다음과 같습니다.
옵션 사용 [autoOpen : false]
$toolTip.dialog("widget").css("visibility", "hidden");
$toolTip.dialog("open");
$toolTip.dialog("widget").css("visibility", "visible");
대화 상자가 보이지 않지만 포커스는 어디에도 설정되지 않고 원래 위치에 유지됩니다. 일반 텍스트만으로도 툴팁에 사용할 수 있지만 시작 순간에 대화 상자를 표시하는 것이 더 중요한 기능성 대화 상자는 테스트되지 않았습니다. 아마 어떤 경우에도 잘 작동합니다.
원래 게시물은 첫 번째 요소에 초점을 맞추지 않기위한 것이지만 대화 상자를 연 후 (내 코드 후) 포커스가 어디에 있어야하는지 쉽게 결정할 수 있습니다.
IE, FF 및 Chrome에서 테스트되었습니다.
잘하면 이것은 누군가를 도울 것입니다.
내 의견으로는이 솔루션은 매우 훌륭합니다.
$("#dialog").dialog({
open: function(event, ui) {
$("input").blur();
}
});
여기에서 찾을 수 없음 : 자동 초점을 제거 할 수없는 UI 대화 상자
비슷한 문제가 있습니다. 유효성 검사에 실패하면 오류 대화 상자를 열고 Flugan이 답변에 표시하는 것처럼 포커스를 잡습니다 . 문제는 대화 상자 내부에 요소가 탭 가능하지 않더라도 대화 상자 자체가 여전히 초점을 맞추고 있다는 것입니다. 다음은 jquery-ui-1.8.23 \ js \ jquery.ui.dialog.js에서 수정되지 않은 원래 코드입니다.
// set focus to the first tabbable element in the content area or the first button
// if there are no tabbable elements, set focus on the dialog itself
$(self.element.find(':tabbable').get().concat(
uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat(
uiDialog.get()))).eq(0).focus();
의견은 그들의 것입니다!
이것은 몇 가지 이유로 나에게 정말 나쁘다. 가장 성가신 것은 사용자의 첫 번째 반응은 마지막 문자를 삭제하기 위해 백 스페이스를 누르는 것이지만, 백 스페이스가 입력 컨트롤 외부에 닿기 때문에 페이지를 떠나라는 메시지가 나타납니다.
다음 해결 방법이 꽤 효과적이라는 것을 알았습니다.
jqueryFocus = $.fn.focus;
$.fn.focus = function (delay, fn) {
jqueryFocus.apply(this.filter(':not(.ui-dialog)'), arguments);
};
다른 문제가 있지만 동일한 원인을 찾고있었습니다. 문제는 대화 상자가 처음 <a href="">.</a>
찾은 것에 초점을 맞추는 것입니다. 따라서 대화 상자에 텍스트가 많고 스크롤 막대가 나타나면 스크롤 막대가 맨 아래로 스크롤되는 상황이 발생할 수 있습니다. 나는 이것이 또한 첫 번째 사람의 질문을 수정한다고 생각합니다. 다른 사람들도 마찬가지입니다.
이해하기 쉬운 간단한 수정. <a id="someid" href="#">.</a>
대화 상자 div의 첫 번째 줄로.
예:
<div id="dialogdiv" title="some title"> <a id="someid" href="#">.</a> <p> //the rest of your stuff </p> </div>
대화가 시작되는 곳
$(somediv).dialog({ modal: true, open: function () { $("#someid").hide(); otherstuff or function }, close: function () { $("#someid").show(); otherstuff or function } });
위의 내용에는 초점이 없으며 스크롤 막대가 속한 상단에 그대로 유지됩니다. 는 <a>
포커스를받을하지만 숨겨져 있습니다. 따라서 전체 효과는 원하는 효과입니다.
I know this is an old thread but as for as the UI docs there is no fix to this. This does not require blur or focus to work. Not sure if it is the most elegant. But it just makes sense and easy to explain to anyone.
If you only have one field in the form of Jquery dialog and it is the one that needs Datepicker, alternatively, you can just set focus on dialog Close (cross) button in dialog's title bar:
$('.ui-dialog-titlebar-close').focus();
Call this AFTER dialog was initialized, e.g.:
$('#yourDialogId').dialog();
$('.ui-dialog-titlebar-close').focus();
Because close button is rendered after the .dialog()
is called.
If you're using dialog buttons, just set the autofocus
attribute on one of the buttons:
$('#dialog').dialog({
buttons: [
{
text: 'OK',
autofocus: 'autofocus'
},
{
text: 'Cancel'
}
]
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<div id="dialog" title="Basic dialog">
This is some text.
<br/>
<a href="www.google.com">This is a link.</a>
<br/>
<input value="This is a textbox.">
</div>
I got the same problem.
The workaround I did is add the dummy textbox at the top of the dialog container.
<input type="text" style="width: 1px; height: 1px; border: 0px;" />
As mentioned, this is a known bug with jQuery UI and should be fixed relatively soon. Until then...
Here's another option, so you don't have to mess with tabindex:
Disable the datepicker temporarily until the dialog box opens:
dialog.find(".datepicker").datepicker("disable");
dialog.dialog({
"open": function() {$(this).find(".datepicker").datepicker("enable");},
});
Works for me.
Duplicate question: How to blur the first form input at the dialog opening
To expand on some of the previous answers (and ignoring the ancillary datepicker aspect), if you want to prevent the focus()
event from focusing the first input field when your dialog opens, try this:
$('#myDialog').dialog(
{ 'open': function() { $('input:first-child', $(this)).blur(); }
});
I had a similar problem and solved it by focusing on the dialog after open:
var $dialog = $("#pnlFiltros")
.dialog({
autoOpen: false,
hide: "puff",
width: dWidth,
height: 'auto',
draggable: true,
resizable: true,
closeOnScape : true,
position: [x,y]
});
$dialog.dialog('open');
$("#pnlFiltros").focus(); //focus on the div being dialogued (is that a word?)
But in my case the first element is an anchor, so I don't know if in your case that will leave the datepicker opened.
EDIT: only works on IE
find in jquery.ui.js
d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus();
and replace with
d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(-1).focus();
jQuery 1.9 is released and there does not appear to be a fix. Attempting to prevent focus of the first text box by some of the suggested methods is not working in 1.9. I think beccause the methods attempt to blur focus or move focus occur AFTER the text box in the dialog has already gained focus and done its dirty work.
I can't see anything in the API documentation that makes me think that anything has changed in terms of expected functionality. Off to add an opener button...
I had similar problem. On my page first input is text box with jQuery UI calendar. Second element is button. As date already have value, I set focus on button, but first add trigger for blur on text box. This solve problem in all browsers and probably in all version of jQuery. Tested in version 1.8.2.
<div style="padding-bottom: 30px; height: 40px; width: 100%;">
@using (Html.BeginForm("Statistics", "Admin", FormMethod.Post, new { id = "FormStatistics" }))
{
<label style="float: left;">@Translation.StatisticsChooseDate</label>
@Html.TextBoxFor(m => m.SelectDate, new { @class = "js-date-time", @tabindex=1 })
<input class="button gray-button button-large button-left-margin text-bold" style="position:relative; top:-5px;" type="submit" id="ButtonStatisticsSearchTrips" value="@Translation.StatisticsSearchTrips" tabindex="2"/>
}
<script type="text/javascript">
$(document).ready(function () {
$("#SelectDate").blur(function () {
$("#SelectDate").datepicker("hide");
});
$("#ButtonStatisticsSearchTrips").focus();
});
This is really important for smartphones and tablets because the keyboard comes up when an input has the focus. This is what I've done, add this input at the beginning of the div:
<input type="image" width="1px" height="1px"/>
Doesn't work with size 0px
. I guess it's even better with a real transparent image, either .png
or .gif
but I haven't tried.
Working fine so far in iPad.
You can Add this :
...
dlg.dialog({ autoOpen:false,
modal: true,
width: 400,
open: function(){ // There is new line
$("#txtStartDate").focus();
}
});
...
as first input : <input type="text" style="position:absolute;top:-200px" />
'IT' 카테고리의 다른 글
PostgreSQL에서 평균을 소수점 이하 2 자리로 반올림하는 방법은 무엇입니까? (0) | 2020.06.09 |
---|---|
정규식을 사용하여 문자를 대문자로 변환 (EditPad Pro) (0) | 2020.06.09 |
(grep) 정규식이 아닌 ASCII 문자와 일치합니까? (0) | 2020.06.09 |
유형이 원시인지 테스트하는 방법 (0) | 2020.06.09 |
두 날짜 사이의 모든 날짜-날짜 인쇄 (0) | 2020.06.09 |