Chrome日期输入框占位符异常覆盖问题的代码解决方案咨询
Great question—this is a super quirky behavior specific to Chrome’s native date input, right? It’s annoying when you delete part of the date (like the month) and the placeholder covers up the remaining bits. Unfortunately, there’s no native HTML fix for this out of the box, but we can hack together a solution using AngularJS logic and a little CSS. Let’s break it down:
Step 1: Update the Input Markup
Add a custom class for targeting and an ng-class directive to toggle placeholder visibility based on partial input:
<input id="tf-datefrom-text" class="form-control date-input" type="date" placeholder="Select date" ng-blur="checkValidation()" min="{{vm.minDate}}" max="{{vm.maxDate}}" ng-model="vm.dateFrom" aria-describedby="basic-addon2" required ng-required="true" ng-class="{'hide-placeholder': vm.hasPartialDate()}" />
Step 2: Add Controller Logic
In your AngularJS controller (the vm scope), add a method to detect partial date input, plus an event listener to sync with real-time changes:
// Check if the input has partial date content (even if ng-model is undefined) vm.hasPartialDate = function() { const inputEl = document.getElementById('tf-datefrom-text'); if (!inputEl) return false; const inputValue = inputEl.value; // If the value is empty, don't hide the placeholder if (!inputValue) return false; // Check if any segment of the date (year/month/day) has content return inputValue.split('-').some(segment => segment.length > 0); }; // Listen for input events to trigger AngularJS digest cycle angular.element(document.getElementById('tf-datefrom-text')).on('input', function() { $scope.$apply(); // Ensures ng-class updates immediately as the user types/deletes });
Step 3: Add CSS to Hide Placeholder
Use a CSS class to make the placeholder invisible when partial input exists:
.date-input.hide-placeholder::placeholder { color: transparent; }
How This Works
- Chrome’s native
dateinput only populatesng-modelwhen a full, valid date is entered—partial entries leavevm.dateFromundefined. That’s why we check the input’s rawvaluedirectly to catch partial fills. - The
hasPartialDatemethod checks if any segment of the date (year, month, or day) has content. If yes, we apply thehide-placeholderclass to make the placeholder disappear. - The
inputevent listener ensures AngularJS updates theng-classin real-time, so the placeholder hides/shows instantly as the user edits the date.
This way, the placeholder only shows when all date segments are empty, and stays hidden when any part of the date is filled—no more overlapping text!
内容的提问来源于stack exchange,提问作者Tomasz Waszczyk

