---
title: "将光标定位于输入框最右侧的实现方式"
author: "zhouyrt"
date: "2012-04-16T23:10:24Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2012-04-16T23:12:22Z"
id: 1487913
url: "https://snandy.iteye.com/blog/1487913"
---

前端开发过程中，经常需要这样的场景。用JS实现将光标定位于输入框最右侧。

 

场景一：编辑图片的描述文字

![](http://dl.iteye.com/upload/attachment/0066/6828/70a3a75b-d713-312e-85eb-ebaa003bb21e.png)

 

场景二：Script.aculo.us的Ajax.InPlaceEditor类。

 

双击可编辑，编辑后离开可自动更新该区域。

 

 

以上场景都需要JS实现将光标定位于输入框最右侧，却不是通过鼠标点入输入框内。

我们知道实现最基本的方法是HTMLElement的focus方法。如下

```
<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>将光标定位于输入框最右侧的实现方式</title>
		<style type="text/css">
			p {
				width: 200px;
				margin: 0 auto;
			}
			input {
				margin: 5px;
			}
		</style>

	</head>
	<body>
		<p>
			<input type="text" value="hello"/>
		</p>
		<script>
			var input = document.getElementsByTagName('input')[0];
			input.focus();
		</script>
	</body>
</html>
```

 

打开该页面会发现，光标位于输入框的最左侧。

 

而现在要实现的是将光标定位于输入框最右侧。需要三个步骤。

 

1，调用focus方法

2，value赋值为空

3，之前的input的值再赋给自己

```
<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>将光标定位于输入框最右侧的实现方式</title>
		<style type="text/css">
			p {
				width: 200px;
				margin: 0 auto;
			}
			input {
				margin: 5px;
			}
		</style>

	</head>
	<body>
		<p>
			<input type="text" value="hello"/>
		</p>
		<script>
			var input = document.getElementsByTagName('input')[0];
			var val = input.value;
			input.focus();
			input.value = '';
			input.value = val;
		</script>
	</body>
</html>
```