$('#toggle').click(function myFunction() {
$('.morphsearchinput').toggleClass('expanded');
});

.morphsearchinput {
-webkit-transition: width .8s ease;
-moz-transition: width .8s ease;
-ms-transition: width .8s ease;
-o-transition: width .8s ease;
transition: width .8s ease;
min-width: 50px; /* min-width as the pixel value */
width: 0%; /* width as the % value */
}
.expanded {
width: 80% !important; /* !important because min-width is stronger than width */
}
body {
background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="morphsearch-form">
<input class="morphsearchinput" type="search" placeholder="Search..." id="toggle" onclick=myfunction()/>
<button class="morphsearch-submit" type="button">Search</button>
</form>
&#13;
想要做的是在点击外部输入类型(即页面上的任何位置)时将搜索恢复到原始宽度(扩展后)。 但我不知道如何实现我可以javascript事件,但然后如何定义该区域。谁能提出建议?
答案 0 :(得分:2)
使用click blur
个事件让它发挥作用。
我还删除了内联onClick
事件,因为您使用jQuery引入它
$('#toggle').on('click blur', function() {
$('.morphsearchinput').toggleClass('expanded');
});
&#13;
.morphsearchinput {
-webkit-transition: width .8s ease;
-moz-transition: width .8s ease;
-ms-transition: width .8s ease;
-o-transition: width .8s ease;
transition: width .8s ease;
min-width: 50px; /* min-width as the pixel value */
width: 0%; /* width as the % value */
}
.expanded {
width: 80% !important; /* !important because min-width is stronger than width */
}
body {
background-color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="morphsearch-form">
<input class="morphsearchinput" type="search" placeholder="Search..." id="toggle" />
<button class="morphsearch-submit" type="button">Search</button>
</form>
&#13;
答案 1 :(得分:0)
尝试添加以下内容:
var morphsearchinput = document.getElementByClassName("morphsearchinput");
window.onclick = function(event) {
if (event.target == morphsearchinput) {
$('.morphsearchinput').toggleClass('expanded');
}
}
答案 2 :(得分:0)
试试这个:
$('#toggle').focusin(function myFunction(){
$('.morphsearchinput').addClass('expanded');
});
$('#toggle').focusout(function myFunction(){
$('.morphsearchinput').removeClass('expanded');
});