将包裹文本的矩形display设置为inline-block,宽度设置为auto即可。
<div >
Winner Left Winner Left
</div>
div{
width: auto
height: auto
padding:1em
border-radius:1em
background: orange
display:inline-block
}
效果
var len = prompt("输入正方形的行数", 0)len = len >10 ? 10 : len
for(var i = 0i <leni++){
for(var j = 0j <lenj++){
document.write("*")
}
document.write("<br / >")
}
<!--<a href="https://www.baidu.com/s?wd=DOCTYPE&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1dBP1n3PjTknAP9nH7hnvFW0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1R1P16kPjn4Pf" target="_blank" class="baidu-highlight" -->DOCTYPE html>
<meta charset="gb2312">
<title></title>
<style type="text/css">
.box {
background: #f00
width: 0px
height: 0px
position: absolute
opacity: 0.5
cursor: move
}
</style>
<script type="text/javascript">
window.onload = function(e) {
e = e || window.event
// startX, startY 为鼠标点击时初始坐标
// diffX, diffY 为鼠标初始坐标与 box 左上角坐标之差,用于拖动
var startX, startY, diffX, diffY
// 是否拖动,初始为 false
var dragging = false
// 鼠标按下
document.onmousedown = function(e) {
startX = e.pageX
startY = e.pageY
// 如果鼠标在 box 上被按下
if(e.target.className.match(/box/)) {
// 允许拖动
dragging = true
// 设置当前 box 的 id 为 moving_box
if(document.getElementById("moving_box") !== null) {
document.getElementById("moving_box").removeAttribute("id")
}
e.target.id = "moving_box"
// 计算坐标差值
diffX = startX - e.target.offsetLeft
diffY = startY - e.target.offsetTop
}
else {
// 在页面创建 box
var active_box = document.createElement("div")
active_box.id = "active_box"
active_box.className = "box"
active_box.style.top = startY + 'px'
active_box.style.left = startX + 'px'
document.body.appendChild(active_box)
active_box = null
}
}
// 鼠标移动
document.onmousemove = function(e) {
// 更新 box 尺寸
if(document.getElementById("active_box") !== null) {
var ab = document.getElementById("active_box")
ab.style.width = e.pageX - startX + 'px'
ab.style.height = e.pageY - startY + 'px'
}
// 移动,更新 box 坐标
if(document.getElementById("moving_box") !== null && dragging) {
var mb = document.getElementById("moving_box")
mb.style.top = e.pageY - diffY + 'px'
mb.style.left = e.pageX - diffX + 'px'
}
}
// 鼠标抬起
document.onmouseup = function(e) {
// 禁止拖动
dragging = false
if(document.getElementById("active_box") !== null) {
var ab = document.getElementById("active_box")
ab.removeAttribute("id")
// 如果<a href="https://www.baidu.com/s?wd=%E9%95%BF%E5%AE%BD&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1dBP1n3PjTknAP9nH7hnvFW0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1R1P16kPjn4Pf" target="_blank" class="baidu-highlight">长宽</a>均小于 3px,移除 box
if(ab.offsetWidth < 3 || ab.offsetHeight < 3) {
document.body.removeChild(ab)
}
}
}
}
</script>
<p>点击鼠标左键并拖动绘制矩形</p>