[英]How to prevent element from exceeding his container borders
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace). 我有一个正方形,单击它会出现在随机位置,并且它也会改变大小(例如,如果我有一个30px的框,但距左边框10px,则游戏空间外仍会得到10px)。
sometimes the square exceed his container border 有时广场超出了他的集装箱边界
How can I make sure that the square will never exceed his container? 我如何确保正方形不会超出其容器?
function position() { var positionTop = Math.random() * 100; var positionLeft = Math.random() * 100; var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;" return position; } document.getElementById("shape").onclick = function() { document.getElementById("shape").style.cssText = position(); }
#gameSpace { width: 100%; height: 470px; background: blue; margin: 0; padding-top: 30px; } #playSpace { width: 90%; height: 90%; margin: 0 auto; margin-top: 10px; border: 1px black solid; } #shape { width: 100px; height: 100px; background-color: red; }
<div id="gameSpace"> <div id="playSpace"> <!-- here we put the shape --> <div id="shape"></div> </div> </div>
You can use a specify the range (min/max) in Math.random
function and then use this function Math.floor(Math.random() * (max - min + 1)) + min;
您可以在Math.random
函数中使用指定范围(最小/最大),然后使用此函数Math.floor(Math.random() * (max - min + 1)) + min;
to limit the returned value of the random function between min and max. 将随机函数的返回值限制在最小值和最大值之间。
maxTop
: height of the container - height of shape maxTop
:容器的高度-形状的高度 maxLeft
: width of the container - width of shape maxLeft
:容器的宽度-形状的宽度 minTop
: 0 minTop
:0 minLeft
: 0 minLeft
:0 You need to use
position:absolute
andpx
value on shape for this to work 您需要在形状上使用position:absolute
和px
值,此功能才能起作用
See code snippet: 查看代码段:
function position() { var minTop = 0; var maxTop = document.getElementById("playSpace").clientHeight - document.getElementById("shape").clientHeight; var minLeft = 0; var maxLeft = document.getElementById("playSpace").clientWidth - document.getElementById("shape").clientWidth ; var positionTop = Math.floor(Math.random() * (maxTop - minTop + 1) + minTop); var positionLeft = Math.floor(Math.random() * (maxLeft - minLeft + 1) + minLeft); var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;" return position; } document.getElementById("shape").onclick = function() { document.getElementById("shape").style.cssText = position(); }
#gameSpace { width: 100%; height: 470px; background: blue; margin: 0; padding-top: 30px; text-align:center; } #playSpace { width: 90%; height: 90%; border: 1px black solid; position:relative; display:inline-block; } #shape { width: 100px; height: 100px; background-color: red; }
<div id="gameSpace"> <div id="playSpace"> <!-- here we put the shape --> <div id="shape"></div> </div> </div>
You need to set position: relative;
您需要设置position: relative;
to the parent element and position: absolute;
到父元素和position: absolute;
to the shape
element. 到shape
元素。 Then use max min value for random where max is the parent width/height and subtract the shape
width/height ... 然后将max min值用于随机,其中max是父级宽度/高度,然后减去shape
width / height ...
This is snippet before update 这是更新之前的片段
function position() { var playSpace = document.querySelector('#playSpace'); var shape = document.getElementById("shape"); var maxHeight = playSpace.offsetHeight - shape.offsetHeight; var maxWidth = playSpace.offsetWidth - shape.offsetWidth; var positionTop = Math.random() * (maxHeight - 0) + 0; var positionLeft = Math.random() * (maxWidth - 0) + 0; // think of this like so: // var positionTop = Math.random() * (max - min) + min; // more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;" return position; } document.getElementById("shape").onclick = function() { document.getElementById("shape").style.cssText = position(); }
#gameSpace { width: 100%; height: 470px; background: blue; margin:0; padding-top: 30px; } #playSpace { position: relative; /* add this line */ width: 90%; height: 90%; margin: 0 auto; border: 1px black solid; } #shape { width: 100px; height: 100px; background-color: red; }
<div id="gameSpace"> <div id="playSpace"> <!-- here we put the shape --> <div id="shape"></div> </div> </div>
Updated after comment Not sure how you added the size()
function but probably the problem was with using ...cssText
that you overwrote the changes. 注释后更新不确定如何添加size()
函数,但可能是由于使用了...cssText
而覆盖了...cssText
的更改。 So now I changed the code with passing the element
to the functions and then only change the single CSS statements which need to be changed. 所以现在我通过将element
传递给函数来更改代码,然后仅更改需要更改的单个CSS语句。
function position(element) { var playSpace = document.querySelector('#playSpace'); var shape = document.getElementById("shape"); var maxHeight = playSpace.offsetHeight - shape.offsetHeight; var maxWidth = playSpace.offsetWidth - shape.offsetWidth; var positionTop = Math.random() * (maxHeight - 0) + 0; var positionLeft = Math.random() * (maxWidth - 0) + 0; // think of this like so: // var positionTop = Math.random() * (max - min) + min; // more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random element.style.position = 'absolute'; element.style.top = positionTop + "px"; element.style.left = positionLeft + "px"; } function size(element) { var sizeMath = (Math.random() * 200) + 50; element.style.width = sizeMath + "px"; element.style.height = sizeMath + "px"; } document.getElementById("shape").onclick = function() { size(document.getElementById("shape")); position(document.getElementById("shape")); }
#gameSpace { width: 100%; height: 470px; background: blue; margin:0; padding-top: 30px; } #playSpace { position: relative; /* add this line */ width: 90%; height: 90%; margin: 0 auto; border: 1px black solid; } #shape { width: 100px; height: 100px; background-color: red; }
<div id="gameSpace"> <div id="playSpace"> <!-- here we put the shape --> <div id="shape"></div> </div> </div>
With CSS calc
, limit the position inside playSpace
area (you can use different units, here %
and px
). 使用CSS calc
,可以限制playSpace
区域内的位置(您可以使用不同的单位,这里%
和px
)。
Then with offsetTop
/ offsetLeft
, get the real position of the square and avoid negative positions (when positionTop < 100px
or positionLeft < 100px
). 然后使用offsetTop
/ offsetLeft
,获取正方形的实际位置,并避免使用负位置( positionTop < 100px
或positionLeft < 100px
)。
function position() {
var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;
var position = "position:relative;top: calc(" + positionTop + "% - 100px);left: calc(" + positionLeft + "% - 100px);";
return position;
}
document.getElementById("shape").onclick = function() {
var shapeDiv = document.getElementById("shape");
shapeDiv.style.cssText = position();
var top = shapeDiv.offsetTop;// Result of calc(" + positionTop + "% - 100px) in px
if(top < 0) {
shapeDiv.style.top = '0px';
}
var left = shapeDiv.offsetLeft;// Result of calc(" + positionLeft + "% - 100px) in px
if(left < 0) {
shapeDiv.style.left = '0px';
}
}
Don't forget to add position: relative
to #playSpace
, to get offsetTop/left correct 不要忘记添加position: relative
对于#playSpace
,以获得offsetTop / left正确
#playSpace {
position:relative;/* mandatory */
}
If you set the containing element to position: relative;
如果将包含元素设置为position: relative;
and the inner element with position: absolute;
内部元素的position: absolute;
the inner elements top left right and bottom properties will calculate from the borders of the containing element. 内部元素的左上,右和bottom属性将根据包含元素的边界进行计算。
Here is a good source of css positioning . 这是CSS定位的一个很好的来源 。
In your case additional validation should be set to positionTop and positionLeft. 在您的情况下,应将其他验证设置为positionTop和positionLeft。
positionTop should be in the interval [( shapeHeight/2 ) - (100 - shapeHeight/2 ) ] positionTop的间隔应为[(shapeHeight / 2)-(100-shapeHeight / 2)]
positionLeft should be in the interval [( shapeWidth/2 ) - (100 - shapeWeight/2 ) ] positionLeft的间隔应为[(shapeWidth / 2)-(100-shapeWeight / 2)]
You can get the parent element size, so that in your scirpt, use a condition to prevent the square to exceed. 您可以获取父元素的大小,以便在脚本中使用条件防止平方超出。
function position() {
var maxWidth = document.getElementById("playSpace").offsetWidth;
var maxTop = document.getElementById("playSpace").offsetHeight;
var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;
if (positionTop > maxTop) { positionTop = maxTop;)
if (positionLeft > maxWidth) { positionLeft = maxWidth;)
var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
return position;
}
I'm not sure if .offsetWidth and .offsetHeight works well, but you got the idea :) 我不确定.offsetWidth和.offsetHeight是否工作正常,但您知道了:)
By tweaking just a little your positionTop and positionLeft variable, I managed to keep the square inside. 通过调整一下您的positionTop和positionLeft变量,我设法将正方形保持在内部。 You just need to change the maximum % that it needs to have to not exceed the container. 您只需要更改不超过容器所需的最大百分比即可。 I found that 75% for the top and 80% for the left seems to be the max! 我发现顶部的75%和左侧的80%似乎是最大!
var positionTop = Math.floor(Math.random() * 75) ;
var positionLeft = Math.random() * 80;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.