问题
I have a really simple jQuery script which when an input element is focused on, it expands its width to 250px (using the focusin()
event), and when the focus is lost, it shrinks back to 200px using the focusout()
event. But I'm not sure I'm using the most syntactically efficient code for what I'm trying to achieve. Here is my current code:
$(document).ready(function() {
$('input').focus(function() {
$(this).animate({
width: "250px"
}, 500);
});
$('input').focusout(function() {
$(this).animate({
width: "200px"
}, 500);
});
});
To me however, this seems unnecessarily bulky. I've tried googling around, but I can't get the keywords right to find any results which help me. Surely there is a much simpler method to achieve such an effect, like a toggle? How would I achieve this?
回答1:
I see nothing wrong with what you've done. If you feel you're repeating yourself too much, you might pull out some logic into a animateWidth
function:
$(document).ready(function() {
function animateWidth(element, width) {
element.animate({ width: width }, 500);
}
$('input').focus(function () { animateWidth($(this), '250px'); })
.focusout(function () { animateWidth($(this), '200px'); });
});
来源:https://stackoverflow.com/questions/8692240/thinning-down-a-jquery-focus-script