选择时间范围/默认设置select选项
<!-- * @Author: Gavin itxuelei@gmail.com * @Date: 2021-02-26 11:50:08 * @LastEditors: Gavin itxuelei@gmail.com * @LastEditTime: 2021-03-08 11:46:45 * @Description: --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>选择时间</title> <script src="https://www.jq22.com/jquery/jquery-3.3.1.js"></script> </head> <body style="width: 300px;margin: 40px auto;"> <select id="selectpicker" onchange="setEnd()"> <option value="0">10</option> <option value="1">30</option> <option value="2">半年</option> <option value="3">一年</option> </select> <br> <br> <input type="text" id="start" placeholder="开始时间" disabled> <br> <br> <input type="text" id="end" placeholder="结束时间" disabled> </body> <script> $("#selectpicker").val('2'); var dayArr = [10, 30, 180, 365] // 获取当前时间 var current = dateFormatter(new Date().valueOf()) //默认开始 // 开始时间 $("#start").val(current) setEnd() function setEnd() { var i = $("#selectpicker").val(); console.log(i) var endTime = dateFormatter(new Date().valueOf() + dayArr[i] * 86400 * 1000)//默认结束 $("#end").val(endTime); } // 时间格式 function dateFormatter(value) { if (value == '' || value == undefined) { return value; } var myDate = new Date(value); //获取当前年 var year = myDate.getFullYear(); //获取当前月 var month = myDate.getMonth() + 1; month = month < 10 ? "0" + month : month; //获取当前日 var date = myDate.getDate(); date = date < 10 ? "0" + date : date; var h = myDate.getHours(); //获取当前小时数(0-23) h = h < 10 ? "0" + h : h; var m = myDate.getMinutes(); //获取当前分钟数(0-59) m = m < 10 ? "0" + m : m; var s = myDate.getSeconds(); s = s < 10 ? "0" + s : s; var time = year + '-' + month + "-" + date; return time; } </script> </html>