keep placeholder on focus in IE10

前端 未结 7 1295
Happy的楠姐
Happy的楠姐 2020-11-30 05:42

Under WebKit and Firefox, the text in a input\'s placeholder sticks around on focus—it doesn\'t disappear until input.val

7条回答
  •  一向
    一向 (楼主)
    2020-11-30 05:46

    I thought I'd share the workaround I used to sort this issue as it seems IE11 still doesn't have a fix.

    In my example - IE11 had added my placeholder value as an actual value within the textarea.

    Here's what I had in my template view:

    
    

    Here's what rendered on the front-end in IE11:

    
    

    So as the user focused on the field - their cursor was at the end of the '..message here' string - odd!

    The workaround for me was to add an initial class to the element on load. Then a basic on 'focus' bind event to check if the class was present - if present, it removes val and then also removes the class. So as soon as the user focuses on the field - the value is reset to an empty string.

    Here's the bind event (this particular example was on a dynamically loaded modal - you could simplify this):

    $(document).on( "focus", '.textarea', function () {
        if ($(this).hasClass('placeholder-val-present')) {
            $(this).val("").removeClass('placeholder-val-present');
        }
    });
    

    This works nicely because when the user tabs out of the field - the placeholder is re-added and it works normally as you'd expect in IE11 and all other browsers.

    I'm sure this is quite a niche example - but it may come in handy for others!

提交回复
热议问题