Я столкнулся с проблемой, которая пока кажется неразрешимой, предотвращая меня От завершения всего проекта. < /p>
Когда я ввожу десятичное число, например, «1.» Сначала появляется точка, а затем, когда я продолжаю печатать, число меняется и становится правильно расположенным (например, «1.2»). Я хочу, чтобы ввод велел правильно с самого начала, так что если я набираю «1.» Это сразу показывает как "1." а не ".1". (Калькулятор использует свою собственную кодированную клавиатуру, а не нативную браузер.) Я уже пробовал несколько подходов, ни один из них не работал, но я сохранил последний в примере JS, который я прикрепил ниже, так что это может выглядеть грязно, я знаю об этом
Большое спасибо за любой полезный ввод. < /P>
// Calculator 1
function calculatePercentage() {
const percent = parseFloat(document.getElementById("percentInput").value);
const whole1 = parseFloat(document.getElementById("wholeInput1").value);
const part = parseFloat(document.getElementById("partInput").value);
const whole2 = parseFloat(document.getElementById("wholeInput2").value);
if (!isNaN(percent) && !isNaN(whole1) && whole1 !== 0) {
let result1 = (percent / 100) * whole1;
document.getElementById("result1").value = result1 % 1 === 0 ? result1 : result1.toFixed(3);
} else {
document.getElementById("result1").value = ""; }
// Calculator 2
if (!isNaN(part) && !isNaN(whole2) && whole2 !== 0) {
let percentage = (part / whole2) * 100;
document.getElementById("result2").value = percentage % 1 === 0 ? `${percentage}%` : `${percentage.toFixed(3)}%`;
} else {
document.getElementById("result2").value = "";
}
}
const input = document.getElementById("wholeInput1", "wholeInput2", "partInput", "percentInput");
input.addEventListener("input", (event) => {
input.value = input.value.replace(/[^0-9.-]/g, "");
});
// highlighted button when active session
document.addEventListener('DOMContentLoaded', function () {
const navLinks = document.querySelectorAll('.navButton');
const sections = document.querySelectorAll('.section');
function highlightActiveSection() {
let currentSection = null;
// Check which section is currently in view
sections.forEach(section => {
const rect = section.getBoundingClientRect();
if (rect.top = window.innerHeight / 2) {
currentSection = section.id;
}
});
// Highlight the correct nav link
navLinks.forEach(link => {
const parentLi = link.parentElement; // Get the of the link
if (link.getAttribute('href').substring(1) === currentSection) {
parentLi.classList.add('active');
} else {
parentLi.classList.remove('active');
}
});
}
// Initial highlight check
highlightActiveSection();
// Highlight on scroll
window.addEventListener('scroll', highlightActiveSection);
});
////////
// Keypad and input field
const numKeypad = document.querySelector('.num-keypad');
const inputFields = document.querySelectorAll('.numberInput'); // All number input fields
let activeInput = null; // Track the active input field
// Show keypad on focus
inputFields.forEach(input => {
input.addEventListener('focus', function () {
numKeypad.classList.remove('hidden');
activeInput = input; // Set the currently focused input
});
input.addEventListener('input', function () {
// Automatically correct the input format during typing
this.value = formatInput(this.value);
// Scroll to the right to ensure the latest input is visible
this.scrollLeft = this.scrollWidth;
});
});
// Hide keypad when clicking outside
document.addEventListener('click', function (e) {
if (!numKeypad.contains(e.target) && !Array.from(inputFields).some(input => input.contains(e.target))) {
numKeypad.classList.add('hidden');
}
});
// Handle number and backspace button clicks
numKeypad.addEventListener('click', function (e) {
const button = e.target;
if (button.classList.contains('num-button')) {
const value = button.dataset.value; // Get the number or dot value
const action = button.dataset.action; // Check if it's a backspace button
if (activeInput) { // Ensure there is an active input field
if (action === 'backspace') {
activeInput.value = activeInput.value.slice(0, -1); // Remove the last character
} else if (value === '.' && activeInput.value.includes('.')) {
// Prevent adding another dot if one already exists
return;
} else if (value === '.' && (activeInput.value === '' || activeInput.value === '-')) {
// Allow `0.` to start if input is empty or has a negative sign
activeInput.value += '0.';
} else if (value) {
activeInput.value += value; // Append the value to the active input field
}
// Trigger the calculation after the input is updated
calculatePercentage();
// Ensure the input scrolls to the latest character
activeInput.scrollLeft = activeInput.scrollWidth;
}
}
});
Подробнее здесь: https://stackoverflow.com/questions/793 ... nput-field
Мобильная версия