Как реализовать кнопки над полем для ввода текста?

Ссылка скопирована
2 ответов

Как реализовать кнопки вставки символов над полям для вводе текста?

Как реализовать кнопки над полем для ввода текста?

Как добавлять текст в textarea туда, где находится курсор? Как добавлять текст до, и после выделенной области? Как это все привязать к кнопкам?

ДОПОЛНЕНО:
Нашел шаблон форума (phpbb3) где есть такие кнопки. Нашел файл который по-идее ответчает за написание сообщения. Но там только непонятные для меня скрипты. Возможно, вам он как-то поможет.
spoiler
Файл /phpbb/message/user_form.php

<?php /** * * This file is part of the phpBB Forum Software package. * * @copyright (c) phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */  namespace phpbbmessage;  /** * Class user_form * Allows users to send emails to other users */ class user_form extends form { 	/** @var int */ 	protected $recipient_id; 	/** @var array */ 	protected $recipient_row; 	/** @var string */ 	protected $subject;  	/** 	* Get the data of the recipient 	* 	* @param int $user_id 	* @return	false|array		false if the user does not exist, array otherwise 	*/ 	protected function get_user_row($user_id) 	{ 		$sql = 'SELECT user_id, username, user_colour, user_email, user_allow_viewemail, user_lang, user_jabber, user_notify_type 			FROM ' . USERS_TABLE . ' 			WHERE user_id = ' . (int) $user_id . ' 				AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')'; 		$result = $this->db->sql_query($sql); 		$row = $this->db->sql_fetchrow($result); 		$this->db->sql_freeresult($result);  		return $row; 	}  	/** 	* {inheritDoc} 	*/ 	public function check_allow() 	{ 		$error = parent::check_allow(); 		if ($error) 		{ 			return $error; 		}  		if (!$this->auth->acl_get('u_sendemail')) 		{ 			return 'NO_EMAIL'; 		}  		if ($this->recipient_id == ANONYMOUS || !$this->config['board_email_form']) 		{ 			return 'NO_EMAIL'; 		}  		if (!$this->recipient_row) 		{ 			return 'NO_USER'; 		}  		// Can we send email to this user? 		if (!$this->recipient_row['user_allow_viewemail'] && !$this->auth->acl_get('a_user')) 		{ 			return 'NO_EMAIL'; 		}  		return false; 	}  	/** 	* {inheritDoc} 	*/ 	public function bind(phpbbrequestrequest_interface $request) 	{ 		parent::bind($request);  		$this->recipient_id = $request->variable('u', 0); 		$this->subject = $request->variable('subject', '', true);  		$this->recipient_row = $this->get_user_row($this->recipient_id); 	}  	/** 	* {inheritDoc} 	*/ 	public function submit(messenger $messenger) 	{ 		if (!$this->subject) 		{ 			$this->errors[] = $this->user->lang['EMPTY_SUBJECT_EMAIL']; 		}  		if (!$this->body) 		{ 			$this->errors[] = $this->user->lang['EMPTY_MESSAGE_EMAIL']; 		}  		$this->message->set_template('profile_send_email'); 		$this->message->set_subject($this->subject); 		$this->message->set_body($this->body); 		$this->message->add_recipient_from_user_row($this->recipient_row);  		parent::submit($messenger); 	}  	/** 	* {inheritDoc} 	*/ 	public function render(phpbbtemplatetemplate $template) 	{ 		parent::render($template);  		$template->assign_vars(array( 			'S_SEND_USER'			=> true, 			'S_POST_ACTION'			=> append_sid($this->phpbb_root_path . 'memberlist.' . $this->phpEx, 'mode=email&u=' . $this->recipient_id),  			'L_SEND_EMAIL_USER'		=> $this->user->lang('SEND_EMAIL_USER', $this->recipient_row['username']), 			'USERNAME_FULL'			=> get_username_string('full', $this->recipient_row['user_id'], $this->recipient_row['username'], $this->recipient_row['user_colour']), 			'SUBJECT'				=> $this->subject, 			'MESSAGE'				=> $this->body, 		)); 	} }

<?php /** * * This file is part of the phpBB Forum Software package. * * @copyright (c) phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ namespace phpbbmessage; /** * Class user_form * Allows users to send emails to other users */ class user_form extends form { /** @var int */ protected $recipient_id; /** @var array */ protected $recipient_row; /** @var string */ protected $subject; /** * Get the data of the recipient * * @param int $user_id * @return false|array false if the user does not exist, array otherwise */ protected function get_user_row($user_id) { $sql = 'SELECT user_id, username, user_colour, user_email, user_allow_viewemail, user_lang, user_jabber, user_notify_type FROM ' . USERS_TABLE . ' WHERE user_id = ' . (int) $user_id . ' AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')'; $result = $this->db->sql_query($sql); $row = $this->db->sql_fetchrow($result); $this->db->sql_freeresult($result); return $row; } /** * {inheritDoc} */ public function check_allow() { $error = parent::check_allow(); if ($error) { return $error; } if (!$this->auth->acl_get('u_sendemail')) { return 'NO_EMAIL'; } if ($this->recipient_id == ANONYMOUS || !$this->config['board_email_form']) { return 'NO_EMAIL'; } if (!$this->recipient_row) { return 'NO_USER'; } // Can we send email to this user? if (!$this->recipient_row['user_allow_viewemail'] && !$this->auth->acl_get('a_user')) { return 'NO_EMAIL'; } return false; } /** * {inheritDoc} */ public function bind(phpbbrequestrequest_interface $request) { parent::bind($request); $this->recipient_id = $request->variable('u', 0); $this->subject = $request->variable('subject', '', true); $this->recipient_row = $this->get_user_row($this->recipient_id); } /** * {inheritDoc} */ public function submit(messenger $messenger) { if (!$this->subject) { $this->errors[] = $this->user->lang['EMPTY_SUBJECT_EMAIL']; } if (!$this->body) { $this->errors[] = $this->user->lang['EMPTY_MESSAGE_EMAIL']; } $this->message->set_template('profile_send_email'); $this->message->set_subject($this->subject); $this->message->set_body($this->body); $this->message->add_recipient_from_user_row($this->recipient_row); parent::submit($messenger); } /** * {inheritDoc} */ public function render(phpbbtemplatetemplate $template) { parent::render($template); $template->assign_vars(array( 'S_SEND_USER' => true, 'S_POST_ACTION' => append_sid($this->phpbb_root_path . 'memberlist.' . $this->phpEx, 'mode=email&u=' . $this->recipient_id), 'L_SEND_EMAIL_USER' => $this->user->lang('SEND_EMAIL_USER', $this->recipient_row['username']), 'USERNAME_FULL' => get_username_string('full', $this->recipient_row['user_id'], $this->recipient_row['username'], $this->recipient_row['user_colour']), 'SUBJECT' => $this->subject, 'MESSAGE' => $this->body, )); } }

ДОПОЛНЕНО2:
Похоже, задача, всё-же не такая легкая как я думал, раз за сутки ничего толком не прояснилось. Жаль...

Дополнительно:

Геннадий, конкретизировал.

  • RimmaKur,тут
  • Как добавлять текст в textarea туда, где находится курсор?

    Это не textarea.

  • ThunderCat,

    Как реализовать кнопки над полем для ввода текста?

  • RimmaKur, Сорян, я невнимательно прочел вопрос, чет решил что кнопки должны быть в текстареа, видимо сонный был ))
  • ThunderCat, бывает
  • Ответы:

    Есть сравнительно старая статья - https://jh3y.medium.com/how-to-where-s-the-caret-g...
    Но там приведен пример определения позиции курсора - https://codepen.io/jh3y/pen/rpoxxL

    • Лично мне код не понятен, но уже хоть что-то. Спасибо!
    Нужно решить такую задачу?

    Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

    Заказать помощь
    Лучший ответ
    1
    Никита Орлов Ответ

    Для реализации кнопок над полем для ввода текста можно использовать HTML и CSS. Вот пример кода:

    ```html

    .button-container {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    }

    .button {
    padding: 5px 10px;
    background-color: #007bff;
    color: #fff;
    border: none;
    cursor: pointer;
    }

    .input-field {
    padding: 10px;
    width: 100%;
    border: 1px solid #ccc;
    border-radius: 5px;
    }



    ```

    В данном примере создается контейнер для кнопок с классом "button-container", в котором размещаются кнопки с классом "button". Под контейнером располагается поле для ввода текста с классом "input-field".

    CSS стили задают отступы, цвета и размеры элементов. Кнопки выравниваются по горизонтали с помощью свойства "justify-content: space-between". Поле для ввода текста имеет закругленные углы и рамку.

    Вы можете настраивать стили кнопок и поля для ввода текста по вашему усмотрению, добавляя или изменяя свойства CSS. Важно помнить, что данный код представляет лишь основу и может быть доработан в зависимости от требований и дизайна вашего проекта.

    Другие ответы (1) Ответить на вопрос
    Алексей Денисов

    Для реализации кнопок над полем для ввода текста веб-приложении можно использовать HTML и CSS. Вот пример кода, который покажет вам, как это сделать:

    1. HTML код:
    ```html


    ```

    2. CSS код:
    ```css
    .input-container {
    position: relative;
    }

    input[type="text"] {
    padding: 10px;
    width: 70%;
    border: 1px solid #ccc;
    border-radius: 5px;
    }

    button {
    position: absolute;
    top: 0;
    right: 0;
    padding: 10px 20px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    }

    button:hover {
    background-color: #0056b3;
    }
    ```

    3. JavaScript код:
    ```javascript
    function myFunction() {
    var input = document.getElementById("myInput").value;
    alert("Вы ввели: " + input);
    }

    function myFunction2() {
    var input = document.getElementById("myInput").value;
    console.log("Вы ввели: " + input);
    }
    ```

    В данном примере создается контейнер для поля ввода текста и двух кнопок. При клике на кнопку "Кнопка 1" будет выводиться алерт с введенным текстом, а при клике на кнопку "Кнопка 2" текст будет выводиться в консоль браузера.

    Вы можете стилизовать кнопки и поле ввода текста с помощью CSS по вашему усмотрению. Надеюсь, это поможет вам реализовать функционал кнопок над полем для ввода текста в вашем веб-приложении.

    комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    Вам также может быть интересно