Случайное положение дочерних елементов
Всем привет! Есть скрипт <https://codepen.io/kotya_ra/pen/pojrNxN> , дающий возможность зажиманием мышки передвигаться( скролить блок), и рандомно распологать дочерние элементы (img) в этом блоке. Как расположить дочерние элементы рандомно, но с расстоянием между ними? Исключить наложение друг на друга. Проблема на картинках :
Так на данный момент :
Так должно быть :
Ответы (1 шт):
Если "дёшево и сердито", то проще всего сделать так:
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
factory((root.dragscroll = {}));
}
})(this, function(exports) {
var _window = window;
var _document = document;
var mousemove = "mousemove";
var mouseup = "mouseup";
var mousedown = "mousedown";
var EventListener = "EventListener";
var addEventListener = "add" + EventListener;
var removeEventListener = "remove" + EventListener;
var newScrollX, newScrollY;
var dragged = [];
var reset = function(i, el) {
for (i = 0; i < dragged.length;) {
el = dragged[i++];
el = el.container || el;
el[removeEventListener](mousedown, el.md, 0);
_window[removeEventListener](mouseup, el.mu, 0);
_window[removeEventListener](mousemove, el.mm, 0);
}
// cloning into array since HTMLCollection is updated dynamically
dragged = [].slice.call(_document.getElementsByClassName("dragscroll"));
for (i = 0; i < dragged.length;) {
(function(el, lastClientX, lastClientY, pushed, scroller, cont) {
(cont = el.container || el)[addEventListener](
mousedown,
(cont.md = function(e) {
if (!el.hasAttribute("nochilddrag") ||
_document.elementFromPoint(e.pageX, e.pageY) == cont
) {
pushed = 1;
lastClientX = e.clientX;
lastClientY = e.clientY;
e.preventDefault();
}
}),
0
);
_window[addEventListener](
mouseup,
(cont.mu = function() {
pushed = 0;
}),
0
);
_window[addEventListener](
mousemove,
(cont.mm = function(e) {
if (pushed) {
(scroller = el.scroller || el).scrollLeft -= newScrollX = -lastClientX + (lastClientX = e.clientX);
scroller.scrollTop -= newScrollY = -lastClientY + (lastClientY = e.clientY);
if (el == _document.body) {
(scroller = _document.documentElement).scrollLeft -= newScrollX;
scroller.scrollTop -= newScrollY;
}
}
}),
0
);
})(dragged[i++]);
}
};
if (_document.readyState == "complete") {
reset();
} else {
_window[addEventListener]("load", reset, 0);
}
exports.reset = reset;
});
$(document).ready(function() {
$(".dragscroll img").each(function() {
$(this).css({
marginLeft: Math.floor(Math.random() * 50),
marginTop: Math.floor(5 + Math.random() * 50),
verticalAlign: ['baseline', 'bottom', 'middle', 'sub', 'super', 'text-bottom', 'text-top', 'top'][Math.floor(Math.random() * 7)]
});
});
});
.dragscroll {
position: relative;
overflow: hidden;
width: 100%;
height: 100vh;
padding: 20px;
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: -o-grab;
cursor: grab;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dragscroll">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
</div>
Чтобы изображения не только псевдохаотично располагались, но и менялся их порядок, нужно добавить перемешивание полученной коллекции и замену элементов согласно новой очерёдности:
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
factory((root.dragscroll = {}));
}
})(this, function(exports) {
var _window = window;
var _document = document;
var mousemove = "mousemove";
var mouseup = "mouseup";
var mousedown = "mousedown";
var EventListener = "EventListener";
var addEventListener = "add" + EventListener;
var removeEventListener = "remove" + EventListener;
var newScrollX, newScrollY;
var dragged = [];
var reset = function(i, el) {
for (i = 0; i < dragged.length;) {
el = dragged[i++];
el = el.container || el;
el[removeEventListener](mousedown, el.md, 0);
_window[removeEventListener](mouseup, el.mu, 0);
_window[removeEventListener](mousemove, el.mm, 0);
}
// cloning into array since HTMLCollection is updated dynamically
dragged = [].slice.call(_document.getElementsByClassName("dragscroll"));
for (i = 0; i < dragged.length;) {
(function(el, lastClientX, lastClientY, pushed, scroller, cont) {
(cont = el.container || el)[addEventListener](
mousedown,
(cont.md = function(e) {
if (!el.hasAttribute("nochilddrag") ||
_document.elementFromPoint(e.pageX, e.pageY) == cont
) {
pushed = 1;
lastClientX = e.clientX;
lastClientY = e.clientY;
e.preventDefault();
}
}),
0
);
_window[addEventListener](
mouseup,
(cont.mu = function() {
pushed = 0;
}),
0
);
_window[addEventListener](
mousemove,
(cont.mm = function(e) {
if (pushed) {
(scroller = el.scroller || el).scrollLeft -= newScrollX = -lastClientX + (lastClientX = e.clientX);
scroller.scrollTop -= newScrollY = -lastClientY + (lastClientY = e.clientY);
if (el == _document.body) {
(scroller = _document.documentElement).scrollLeft -= newScrollX;
scroller.scrollTop -= newScrollY;
}
}
}),
0
);
})(dragged[i++]);
}
};
if (_document.readyState == "complete") {
reset();
} else {
_window[addEventListener]("load", reset, 0);
}
exports.reset = reset;
});
$(document).ready(function() {
let aIMGs = [...$(".dragscroll img")].sort(() => Math.random() - 0.5);
$parent = $("div.dragscroll");
aIMGs.forEach(function(el) {
$(el).css({
marginLeft: Math.floor(Math.random() * 50),
marginTop: Math.floor(5 + Math.random() * 50),
verticalAlign: ['baseline', 'bottom', 'middle', 'sub', 'super', 'text-bottom', 'text-top', 'top'][Math.floor(Math.random() * 7)]
});
$parent.append($(el));
});
});
.dragscroll {
position: relative;
overflow: hidden;
width: 100%;
height: 100vh;
padding: 20px;
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: -o-grab;
cursor: grab;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dragscroll">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
<img src="https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg" width="200px" height="auto">
<img src="https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png" width="200px" height="auto">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg" width="200px" height="auto">
<img src="https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg" width="200px" height="auto">
</div>
Развивая тему, можно (даже нужно) поместить изображения (вернее, ссылки на них) сразу в массив и на их основе заполнить контейнер (например, при динамическом изменении всё равно придётся к этому вернуться):
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
factory((root.dragscroll = {}));
}
})(this, function(exports) {
var _window = window;
var _document = document;
var mousemove = "mousemove";
var mouseup = "mouseup";
var mousedown = "mousedown";
var EventListener = "EventListener";
var addEventListener = "add" + EventListener;
var removeEventListener = "remove" + EventListener;
var newScrollX, newScrollY;
var dragged = [];
var reset = function(i, el) {
for (i = 0; i < dragged.length;) {
el = dragged[i++];
el = el.container || el;
el[removeEventListener](mousedown, el.md, 0);
_window[removeEventListener](mouseup, el.mu, 0);
_window[removeEventListener](mousemove, el.mm, 0);
}
// cloning into array since HTMLCollection is updated dynamically
dragged = [].slice.call(_document.getElementsByClassName("dragscroll"));
for (i = 0; i < dragged.length;) {
(function(el, lastClientX, lastClientY, pushed, scroller, cont) {
(cont = el.container || el)[addEventListener](
mousedown,
(cont.md = function(e) {
if (!el.hasAttribute("nochilddrag") ||
_document.elementFromPoint(e.pageX, e.pageY) == cont
) {
pushed = 1;
lastClientX = e.clientX;
lastClientY = e.clientY;
e.preventDefault();
}
}),
0
);
_window[addEventListener](
mouseup,
(cont.mu = function() {
pushed = 0;
}),
0
);
_window[addEventListener](
mousemove,
(cont.mm = function(e) {
if (pushed) {
(scroller = el.scroller || el).scrollLeft -= newScrollX = -lastClientX + (lastClientX = e.clientX);
scroller.scrollTop -= newScrollY = -lastClientY + (lastClientY = e.clientY);
if (el == _document.body) {
(scroller = _document.documentElement).scrollLeft -= newScrollX;
scroller.scrollTop -= newScrollY;
}
}
}),
0
);
})(dragged[i++]);
}
};
if (_document.readyState == "complete") {
reset();
} else {
_window[addEventListener]("load", reset, 0);
}
exports.reset = reset;
});
$(document).ready(function() {
$parent = $("div.dragscroll");
// Если требуется перемешать
// aIMGs.sort(() => Math.random() - 0.5).forEach(function(el) {
aIMGs.forEach(function(el) {
let oImg = new Image();
oImg.src = el;
$(oImg).css({
width: 200,
height: 'auto',
marginLeft: Math.floor(5 + Math.random() * 50),
marginTop: Math.floor(5 + Math.random() * 50),
verticalAlign: ['baseline', 'bottom', 'middle', 'sub', 'super', 'text-bottom', 'text-top', 'top'][Math.floor(Math.random() * 7)]
});
$parent.append($(oImg));
});
});
let aIMGs = ["https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg","https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png","https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg","https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg","https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg","https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png","https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg","https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg","https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg","https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png","https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg","https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg","https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg","https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png","https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg","https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg","https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg","https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png","https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg","https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg","https://ichef.bbci.co.uk/news/1024/cpsprodpb/83D7/production/_111515733_gettyimages-1208779325.jpg","https://sjferret.com/wp-content/uploads/Thinking-of-getting-a-cat.png","https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg","https://www.interfax.ru/ftproot/textphotos/2019/05/17/700gc.jpg"];
.dragscroll {
position: relative;
overflow: hidden;
width: 100%;
height: 100vh;
padding: 20px;
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: -o-grab;
cursor: grab;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dragscroll"></div>

