鼠标焦点在input的某个位置上,点击一个button 在input光标处的增加文字

截图

html

<table class="table table-bordered table_url">
                    <tr>
                        <th>域名</th>
                        <td>
                            <input type="text" style="width:500px;" name="site_name" required value=""
                                   placeholder="请输入域名"/>
                            <span class="form-required">*</span>
                            例如:baidu.com
                        </td>
                    </tr>
                    <tr>
                        <th>关键字</th>
                        <td>
                            <button class="btn btn-primary model_name" type="button">{1}</button>
                            <button class="btn btn-primary model_name" type="button">{2}</button>
                            <button class="btn btn-primary model_name" type="button">{3}</button>
                        </td>
                    </tr>
                    <tr>
                        <th>url字符串</th>
                        <td>
                            <div>
                                <input type="text" style="width:500px;" name="start_id" required value=""
                                       placeholder="请输入整数" oninput="value=value.replace(/[^\d]/g,'')"/>
                                <span class="fas del_urls"><i class="fa fa-minus-circle" style="color: red"></i></span>
                            </div>
                            <div style="margin-top: 10px">
                                <input type="text" style="width: 500px" name="model" required value=""
                                       placeholder="由{}拼接的字符串">
                                <span class="fas del_url"><i class="fa fa-minus-circle"></i></span>
                                <span class="fas add_url"><i class="fa fa-plus-circle"></i></span>
                            </div>
                        </td>
                    </tr>
                </table>

js

        var lastInput = null;
        //记录最后一次光标焦点所在的input框
        // $(".table_url input").focus(function () {//不能对未来添加的input框产生事件
        //     lastInput = this;
        // });
        $(document).on('focus', '.table_url input', function () {//可对未来添加的input框产生事件
            lastInput = this;
        });

        $(".model_name").click(function () {
            //锁定最后一次光标的input框
            if (lastInput) {
                lastInput.focus();
            } else {
                console.log('null');
                return;
            }
            //修改内容
            var str = $(this).text();
            if (typeof document.selection != "undefined") {
                document.selection.createRange().text = str;
            } else {
                lastInput.value = lastInput.value.substr(0, lastInput.selectionStart) + str + lastInput.value.substring(lastInput.selectionStart, lastInput.value.length);
            }
        });
posted @ 2020-11-09 17:00  王玉岩  阅读(630)  评论(0编辑  收藏  举报